-
Notifications
You must be signed in to change notification settings - Fork 0
/
2. Add Two Numbers
69 lines (68 loc) · 1.95 KB
/
2. Add Two Numbers
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(-1)
pre = dummy_head
carry = False
while l1 and l2:
num1 = l1.val
num2 = l2.val
if carry:
summ = num1 + num2 + 1
if summ >= 10:
pre.next = ListNode(summ - 10)
carry = True
else:
pre.next = ListNode(summ)
carry = False
else:
summ = num1 + num2
if summ >= 10:
pre.next = ListNode(summ - 10)
carry = True
else:
pre.next = ListNode(summ)
carry = False
pre = pre.next
l1 = l1.next
l2 = l2.next
while l1:
if carry:
summ = l1.val + 1
if summ >= 10:
pre.next = ListNode(summ - 10)
carry = True
else:
pre.next = ListNode(summ)
carry = False
l1 = l1.next
pre = pre.next
else:
pre.next = l1
break
while l2:
if carry:
summ = l2.val + 1
if summ >= 10:
pre.next = ListNode(summ - 10)
carry = True
else:
pre.next = ListNode(summ)
carry = False
l2 = l2.next
pre = pre.next
else:
pre.next = l2
break
if carry:
pre.next = ListNode(1)
return dummy_head.next