-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Two Numbers
38 lines (37 loc) · 1.12 KB
/
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
# 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: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
ptr1=l1
ptr2=l2
carry=0
dummy=ListNode()
tail=dummy
while ptr1 and ptr2:
summation=ptr1.val + ptr2.val + carry
result=summation%10
carry=summation//10
tail.next=ListNode(result)
tail=tail.next
ptr1=ptr1.next
ptr2=ptr2.next
while ptr1:
summation=ptr1.val + carry
result=summation%10
carry=summation//10
tail.next=ListNode(result)
tail=tail.next
ptr1=ptr1.next
while ptr2:
summation=ptr2.val + carry
result=summation%10
carry=summation//10
tail.next=ListNode(result)
tail=tail.next
ptr2=ptr2.next
if carry:
tail.next=ListNode(carry)
return dummy.next