We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 29dd2cc commit b379264Copy full SHA for b379264
0002-add-two-numbers/0002-add-two-numbers.py
@@ -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