-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path2_Add_Two_Numbers.py
More file actions
31 lines (28 loc) · 925 Bytes
/
2_Add_Two_Numbers.py
File metadata and controls
31 lines (28 loc) · 925 Bytes
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
# 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]:
m = 0
head = curr = ListNode(0)
while(l1 and l2):
curr_sum = l1.val + l2.val + m
m = curr_sum//10
curr.next = ListNode(curr_sum % 10)
curr = curr.next
l1 = l1.next
l2 = l2.next
if l1 or l2:
l = l1 if l1 else l2
while(l):
curr_sum = l.val + m
m = curr_sum//10
curr.next = ListNode(curr_sum % 10)
curr = curr.next
l = l.next
if m != 0:
curr.next = ListNode(m)
curr = curr.next
return head.next