Leetcode 刷題之路 2. Add two numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807.
Repeat question:
有兩個非空鏈表,代表兩個非負整數,數字在鏈表內逆序存儲,求兩個數的和,並用同樣的逆序方式存儲在鏈表中。
Solution:
解法一
設一個函數number(), 將一個鏈錶轉換成整型的數, 用這個函數計算兩個鏈表的整數然後求和。 求和完後,將這個整數變為字元串數組形式,然後將逆序後的數組的每一個元素變為整型後寫入鏈表。
解法二
考慮到number()函數如果計算的數字過大會越界,我們改良number()函數為stringNumber(), 這個函數依次將鏈表中的每一位存入數組。在求和函數中,調用這個函數以此求得兩個數組並逆序,設置flag表示是否有進位,初始值為0. 然後每次彈出兩個數組的整數並相加再加上flag, 直到兩個數組都為空了結束。
Code:
解法一:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: def number(self, l): count = 0 result = 0 while l: result += l.val* 10**count l = l.next count +=1 return result def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ result = self.number(l1)+ self.number(l2) result = str(result) head = None for i, res in enumerate(result[::-1]): if i is 0: l = ListNode(int(res)) head = l else: l.next = ListNode(int(res)) l = l.next return head
解法二:
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution: def stringNumber(self, l): result = [] while l: result.append(l.val) l = l.next return result def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ number1 = self.stringNumber(l1)[::-1] number2 = self.stringNumber(l2)[::-1] result = [] flag = 0 while number1 or number2 or flag: if number1 and number2: res = number1.pop() + number2.pop() + flag if res > 9: flag = 1 else: flag = 0 result.append(res%10) elif number1: res = number1.pop() + flag if res > 9: flag = 1 else: flag = 0 result.append(res%10) elif number2: res = number2.pop() + flag if res > 9: flag = 1 else: flag = 0 result.append(res%10) else: if flag: result.append(flag) flag = 0 head = None for i, res in enumerate(result): if i is 0: l = ListNode(int(res)) head = l else: l.next = ListNode(int(res)) l = l.next return head
Test case:
l1: 0->1l2: 0->1—>2l1: 9->9l2: 1l1: 1->2->3........->9l1: 1->2->3....... ->9
Complexity analysis:
Time complexity: O(max(m, n)). assume that m and n represents the length of l1 and l2 respectively, the algorithm above iterates at most max(m, n) times.
Follow up:
what if the digits in the linked list are stored in non-reversed order?
(3 -> 4 -> 2) + (4 -> 6 -> 5) = 8 -> 0 -> 7
推薦閱讀:
※【LeetCode】3. 無重複字元的最長子串
※Leetcode-38-Count-and-Say(學渣的痛大神們不懂。。。)
※010 Regular Expression Matching[H]
※【LeetCode】#1——TwoSum
※019 Remove Nth Node From End of List[M]