leetcode02

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
"""
class (object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry1 = 0
result = []
if l1 == None:
while l2 != None:
result.append(l2.val)
l2 = l2.next
elif l2 == None: # l2为空,直接返回l1
while l1 != None:
result.append(l1.val)
l1 = l1.next
else:
while l1 != None or l2 != None:
carry = 0
if l1 == None:
i = 0
else:
i = l1.val
if l2 == None:
j = 0
else:
j = l2.val
sum_num = i + j
if sum_num + carry1 > 9:
sum_num = sum_num - 10
carry = 1
result.append(sum_num + carry1)
if carry == 1:
carry1 = 1
else:
carry1 = 0
if (l1 != None):
l1 = l1.next
if (l2 != None):
l2 = l2.next
if carry1 == 1:
result.append(1)
head = ListNode(result[0])
temp_head = head
for n in result[1:result.__len__()]:
temp = ListNode(n)
temp_head.next = temp
temp_head = temp
return head
if __name__ == "__main__":
a1 = ListNode(1)
# a2 = ListNode(8)
# a3 = ListNode(3)
# a1.next=a2
# a2.next=a3
b1 = ListNode(9)
b2 = ListNode(9)
# b3 = ListNode(4)
b1.next = b2
# b2.next=b3
sol = Solution()
temp = sol.addTwoNumbers(a1, b1)
while temp != None:
print(temp.val)
temp = temp.next