Skip to content

Commit f83a22c

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

File tree

2 files changed

+64
-8
lines changed

2 files changed

+64
-8
lines changed

problems/add-two-numbers-ii.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
First, if you haven't done the [first problem](https://leetcode.com/problems/add-two-numbers/) please do it first. And here is its [answer](https://leetcode.com/problems/add-two-numbers/discuss/43105).
3+
We can just reverse the linked list, and we can use the solution of the [first problem](https://leetcode.com/problems/add-two-numbers/).
4+
So I do this problem without reversing the linked list.
5+
6+
We need to know the length of each linked list. So we can know when do we start adding the `val`.
7+
We need to set the answer to a double linked list. Because we might need to modify the upper digits.
8+
For example 999 + 1.
9+
10+
The time complexity is `O(N)`, `N` is the length of the input linked list.
11+
The space complexity is `O(N)`, too.
12+
"""
13+
class ListNode(object):
14+
def __init__(self, x):
15+
self.val = x
16+
self.next = None
17+
self.prev = None
18+
19+
class Solution(object):
20+
def addTwoNumbers(self, A, B):
21+
l1 = self.getLength(A)
22+
l2 = self.getLength(B)
23+
head = ListNode(0)
24+
curr = head
25+
while A or B:
26+
if l1>l2:
27+
self.addDigit(curr, A.val)
28+
l1-=1
29+
A = A.next
30+
elif l2>l1:
31+
self.addDigit(curr, B.val)
32+
l2-=1
33+
B = B.next
34+
else:
35+
val = (A.val if A else 0) + (B.val if B else 0)
36+
self.addDigit(curr, val)
37+
if l1: l1-=1
38+
if l2: l2-=1
39+
if A: A = A.next
40+
if B: B = B.next
41+
curr = curr.next
42+
return head if head.val else head.next #remove leading zero
43+
44+
def getLength(self, L):
45+
length = 0
46+
while L:
47+
length+=1
48+
L = L.next
49+
return length
50+
51+
def addDigit(self, node, val):
52+
if val<10:
53+
node.next = ListNode(val)
54+
node.next.prev = node
55+
else:
56+
node.next = ListNode(val-10)
57+
node.next.prev = node
58+
node.val+=1
59+
while node.val>=10:
60+
node.prev.val+=1
61+
node.val-=10
62+
node = node.prev

problems/add-two-numbers.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#2019/11/17 Update
12
"""
23
Add numbers, units to units digit, tens to tens digit...
34
If the added number is greater than 9
@@ -18,7 +19,7 @@ def addTwoNumbers(self, l1, l2):
1819
while l1 or l2 or temp:
1920
val = (l1.val if l1 else 0) + (l2.val if l2 else 0) + temp
2021

21-
if val>9:
22+
if val>=10:
2223
temp = 1
2324
val = val-10
2425
else:
@@ -32,13 +33,6 @@ def addTwoNumbers(self, l1, l2):
3233
return pre_head.next
3334

3435

35-
36-
37-
38-
39-
40-
41-
4236
class Solution(object):
4337

4438
#I like this better and it's faster

0 commit comments

Comments
 (0)