-
Notifications
You must be signed in to change notification settings - Fork 1
/
2-add_two_numbers.py
51 lines (40 loc) · 1.09 KB
/
2-add_two_numbers.py
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
"""
https://leetcode.com/problems/add-two-numbers/
A few tricky cases:
[5]
[5]
[0]
[0]
"""
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
BASE = 10
carry = 0
head = ListNode(0)
curr = head
while l1 or l2 or carry:
l1_num, l2_num = 0, 0
if l1:
l1_num = l1.val
l1 = l1.next
if l2:
l2_num = l2.val
l2 = l2.next
digit = carry + l1_num + l2_num
#if we had a 1 carry into this digit
if carry == 1:
carry -= 1
#if we need to carry into the next digit
if digit >= 10:
digit %= BASE
carry += 1
# print(digit, carry)
digit_node = ListNode(digit)
curr.next = digit_node
curr = curr.next
return head.next