Skip to content

Commit 4431aab

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
no message
1 parent 7ab0909 commit 4431aab

File tree

1 file changed

+50
-9
lines changed

1 file changed

+50
-9
lines changed

problems/add-two-numbers.py

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
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+
142
class Solution(object):
243

344
#I like this better and it's faster
@@ -14,18 +55,18 @@ def getTotal(l):
1455
x+=1
1556
l = l.next
1657
return total
17-
58+
1859
total = getTotal(l1)+getTotal(l2)
1960

2061
#put the number back into linked list
2162
num_string = str(total)[::-1]
2263
pre = ListNode(None)
2364
curr = pre
24-
65+
2566
for n in num_string:
2667
curr.next = ListNode(int(n))
2768
curr = curr.next
28-
69+
2970
return pre.next
3071

3172

@@ -45,27 +86,27 @@ def addTwoNumbers(self, l1, l2):
4586

4687
while l1 or l2:
4788
total = carry
48-
89+
4990
if l1:
5091
total+=l1.val
5192
l1 = l1.next
5293
if l2:
5394
total+=l2.val
5495
l2 = l2.next
55-
96+
5697
if total>=10:
5798
carry=1
5899
curr.next = ListNode(total%10)
59100
else:
60101
carry = 0
61102
curr.next = ListNode(total)
62-
103+
63104
curr = curr.next
64-
105+
65106
#check if there is carry left behind, for example
66107
#[5]+[5]=[0,1]
67108
#both linked list are done iterate, but still haven't finish adding
68109
if carry!=0:
69110
curr.next = ListNode(carry)
70-
71-
return pre.next
111+
112+
return pre.next

0 commit comments

Comments
 (0)