Skip to content

Commit b29f198

Browse files
committed
Sync LeetCode submission Runtime - 1 ms (81.58%), Memory - 17.8 MB (15.20%)
1 parent 776b39b commit b29f198

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed

0002-add-two-numbers/solution.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,33 @@
1+
# Approach 1: Elementary Math
2+
3+
# Time: O(max(n, m))
4+
# Space: O(1)
5+
16
# Definition for singly-linked list.
27
# class ListNode:
38
# def __init__(self, val=0, next=None):
49
# self.val = val
510
# self.next = next
11+
612
class Solution:
713
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
8-
result = ListNode(0)
9-
result_list = result
14+
dummy_head = ListNode(0)
15+
curr = dummy_head
1016
carry = 0
11-
12-
while l1 or l2 or carry:
13-
val1 = l1.val if l1 else 0
14-
val2 = l2.val if l2 else 0
15-
sum_val = val1 + val2 + carry
16-
carry = sum_val // 10
17-
ans = sum_val % 10
18-
19-
result_list.next = ListNode(ans)
20-
result_list = result_list.next
17+
18+
while l1 != None or l2 != None or carry != 0:
19+
l1val = l1.val if l1 else 0
20+
l2val = l2.val if l2 else 0
21+
22+
column_sum = l1val + l2val + carry
23+
carry = column_sum // 10
2124

25+
new_node = ListNode(column_sum % 10)
26+
curr.next = new_node
27+
curr = new_node
28+
2229
l1 = l1.next if l1 else None
2330
l2 = l2.next if l2 else None
24-
25-
return result.next
31+
32+
return dummy_head.next
33+

0 commit comments

Comments
 (0)