Skip to content

Commit 17a89c7

Browse files
author
Joseph Luce
authored
Create 002_add_two_numbers.md
1 parent a9a3307 commit 17a89c7

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 2. Add Two Numbers
2+
3+
## Best Solution
4+
- Runtime: O(L1) + O(L2)
5+
- Space: O(L1) + O(L2)
6+
- L1 - Nodes in list 1
7+
- L2 - Nodes in list 2
8+
9+
The only tricky part is the carry over.
10+
You could implement it with a boolean for the carry over, however, I believe it creates more if else statements.
11+
Instead, if you used a rolling sum instead and removed the last digit of the sum, it will be more elegant.
12+
13+
```
14+
class Solution:
15+
def __init__(self):
16+
self._sum = 0
17+
self._dummy_head = ListNode(-1)
18+
self._tail = self._dummy_head
19+
20+
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
21+
while l1 and l2:
22+
digit = self.get_digit(l1.val+l2.val)
23+
self.add_new_node(digit)
24+
l1, l2 = l1.next, l2.next
25+
while l1:
26+
digit = self.get_digit(l1.val)
27+
self.add_new_node(digit)
28+
l1 = l1.next
29+
while l2:
30+
digit = self.get_digit(l2.val)
31+
self.add_new_node(digit)
32+
l2 = l2.next
33+
if self._sum != 0:
34+
self.add_new_node(1)
35+
return self._dummy_head.next
36+
37+
def get_digit(self, _sum):
38+
self._sum += _sum
39+
digit = self._sum % 10
40+
self._sum //= 10
41+
return digit
42+
43+
def add_new_node(self, digit):
44+
new_node = ListNode(digit)
45+
self._tail.next = new_node
46+
self._tail = new_node
47+
```

0 commit comments

Comments
 (0)