forked from coldmanck/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0002_Add_Two_Numbers.py
More file actions
31 lines (28 loc) · 797 Bytes
/
Copy path0002_Add_Two_Numbers.py
File metadata and controls
31 lines (28 loc) · 797 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, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
dummy_head = ListNode(-1)
head = dummy_head
while l1 or l2:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
if val >= 10:
val %= 10
carry = 1
else:
carry = 0
head.next = ListNode(val)
head = head.next
if carry:
head.next = ListNode(carry)
return dummy_head.next