-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_two_numbers.py
41 lines (35 loc) · 939 Bytes
/
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
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
root = ListNode()
p = root
add = 0
while l1 and l2:
l1.val = l1.val + l2.val + add
add = l1.val // 10
l1.val %= 10
p.next = l1
p = p.next
l1 = l1.next
l2 = l2.next
while l1:
l1.val += add
add = l1.val // 10
l1.val %= 10
p.next = l1
p = p.next
l1 = l1.next
while l2:
l2.val += add
add = l2.val // 10
l2.val %= 10
p.next = l2
p = p.next
l2 = l2.next
if add != 0:
p.next = ListNode(add)
return root.next