题目

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def addTwoNumbers(self, l1, l2):
i, j = 0, 0
result = []
add = 0
while i < len(l1) and j < len(l2):
s1 = l1[i] if i < len(l1) else 0
s2 = l2[j] if j < len(l2) else 0
sum = s1 + s2 + add
result += [sum if sum<10 else sum%10]
add = 1 if sum > 10 else 0
i, j = i+1, j+1
return result

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
i, j = l1, l2
result = ListNode(0)
tail = result
add = 0
while i is not None or j is not None:
s1 = i.val if i is not None else 0
s2 = j.val if j is not None else 0
sum = s1 + s2 + add
tail.next = ListNode(sum%10)
tail = tail.next
add = 1 if sum >= 10 else 0
i = i.next if i is not None else None
j = j.next if j is not None else None
if add == 1:
tail.next = ListNode(1)
return result.next