Skip to content

Commit ef08eb0

Browse files
Create 002_Add_Two_Numbers.py
1 parent d87f6dc commit ef08eb0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

002_Add_Two_Numbers.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Definition for singly-linked list.
2+
class ListNode(object):
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
8+
class Solution(object):
9+
def addTwoNumbers(self, l1, l2):
10+
"""
11+
:type l1: ListNode
12+
:type l2: ListNode
13+
:rtype: ListNode
14+
"""
15+
last = 0
16+
head = prev = None
17+
while True:
18+
if l2 is None and l1 is None and last == 0:
19+
break
20+
val = last
21+
if l2 is not None:
22+
val += l2.val
23+
l2 = l2.next
24+
if l1 is not None:
25+
val += l1.val
26+
l1 = l1.next
27+
if val >= 10:
28+
val = val % 10
29+
last = 1
30+
else:
31+
last = 0
32+
current = ListNode(val)
33+
if prev is None:
34+
head = current
35+
else:
36+
prev.next = current
37+
prev = current
38+
return head

0 commit comments

Comments
 (0)