-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.add-two-numbers.py
69 lines (46 loc) · 1.48 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#
# @lc app=leetcode id=2 lang=python3
#
# [2] Add Two Numbers
#
# @lc code=start
# 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:
# add each one and create list nodes while traversing both linked lists
# deal with carry when there's over 10
# consider when l1 or l2 ends
dummy_node = ListNode()
prev_node = dummy_node
carry = 0
while l1 and l2:
temp_sum = l1.val + l2.val + carry
uncarried_sum = temp_sum % 10
carry = temp_sum // 10
# i.e. newly made node
prev_node.next = ListNode(uncarried_sum)
prev_node = prev_node.next
l1 = l1.next
l2 = l2.next
while l1:
temp_sum = l1.val + carry
uncarried_sum = temp_sum % 10
carry = temp_sum // 10
prev_node.next = ListNode(uncarried_sum)
prev_node = prev_node.next
l1 = l1.next
while l2:
temp_sum = l2.val + carry
uncarried_sum = temp_sum % 10
carry = temp_sum // 10
prev_node.next = ListNode(uncarried_sum)
prev_node = prev_node.next
l2 = l2.next
if carry > 0:
prev_node.next = ListNode(carry)
return dummy_node.next
# @lc code=end