-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.addTwoNumbers.py
More file actions
33 lines (29 loc) · 852 Bytes
/
2.addTwoNumbers.py
File metadata and controls
33 lines (29 loc) · 852 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
32
33
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = False
result = ListNode(None)
ptr = result
while l1 or l2 or carry:
value = carry
value += l1.val if l1 else 0
value += l2.val if l2 else 0
carry = False
if value >= 10:
value -= 10
carry = True
newNode = ListNode(value)
ptr.next = newNode
ptr = newNode
l1 = l1.next if l1 else l1
l2 = l2.next if l2 else l2
return result.next