Skip to content

Commit b379264

Browse files
Time: 50 ms (82.65%), Space: 16.6 MB (48.65%) - LeetHub
1 parent 29dd2cc commit b379264

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
8+
result = ListNode()
9+
current = result
10+
carry = 0
11+
12+
while l1 or l2 or carry:
13+
value1 = l1.val if l1 else 0
14+
value2 = l2.val if l2 else 0
15+
16+
# new digit
17+
value = value1 + value2 + carry
18+
# if carry is 10+
19+
carry = value // 10
20+
value = value % 10
21+
current.next = ListNode(value)
22+
23+
# update pointers
24+
current = current.next
25+
l1 = l1.next if l1 else None
26+
l2 = l2.next if l2 else None
27+
28+
return result.next

0 commit comments

Comments
 (0)