1
+ """
2
+ Add numbers, units to units digit, tens to tens digit...
3
+ If the added number is greater than 9
4
+ We will add 1 to next digit (`temp`) and only take the units digit of the added value.
5
+
6
+ For example, if we are adding units digits, 3 and 9, the sum is 12.
7
+ 12 is greater than the 9, so we set `temp` to 1, so when we are calculating tens digits it will `+1`.
8
+ And we only take the units digit of 12, which is `12 - 10 = 2`.
9
+
10
+ The time complexity is O(N), N is the length of two linked list.
11
+ Space complexity is O(N), since we need to store a new linked list.
12
+ """
13
+ class Solution (object ):
14
+ def addTwoNumbers (self , l1 , l2 ):
15
+ temp = 0
16
+ pre_head = ListNode (- 1 )
17
+ curr = pre_head
18
+ while l1 or l2 or temp :
19
+ val = (l1 .val if l1 else 0 ) + (l2 .val if l2 else 0 ) + temp
20
+
21
+ if val > 9 :
22
+ temp = 1
23
+ val = val - 10
24
+ else :
25
+ temp = 0
26
+
27
+ curr .next = ListNode (val )
28
+
29
+ if l1 : l1 = l1 .next
30
+ if l2 : l2 = l2 .next
31
+ curr = curr .next
32
+ return pre_head .next
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
1
42
class Solution (object ):
2
43
3
44
#I like this better and it's faster
@@ -14,18 +55,18 @@ def getTotal(l):
14
55
x += 1
15
56
l = l .next
16
57
return total
17
-
58
+
18
59
total = getTotal (l1 )+ getTotal (l2 )
19
60
20
61
#put the number back into linked list
21
62
num_string = str (total )[::- 1 ]
22
63
pre = ListNode (None )
23
64
curr = pre
24
-
65
+
25
66
for n in num_string :
26
67
curr .next = ListNode (int (n ))
27
68
curr = curr .next
28
-
69
+
29
70
return pre .next
30
71
31
72
@@ -45,27 +86,27 @@ def addTwoNumbers(self, l1, l2):
45
86
46
87
while l1 or l2 :
47
88
total = carry
48
-
89
+
49
90
if l1 :
50
91
total += l1 .val
51
92
l1 = l1 .next
52
93
if l2 :
53
94
total += l2 .val
54
95
l2 = l2 .next
55
-
96
+
56
97
if total >= 10 :
57
98
carry = 1
58
99
curr .next = ListNode (total % 10 )
59
100
else :
60
101
carry = 0
61
102
curr .next = ListNode (total )
62
-
103
+
63
104
curr = curr .next
64
-
105
+
65
106
#check if there is carry left behind, for example
66
107
#[5]+[5]=[0,1]
67
108
#both linked list are done iterate, but still haven't finish adding
68
109
if carry != 0 :
69
110
curr .next = ListNode (carry )
70
-
71
- return pre .next
111
+
112
+ return pre .next
0 commit comments