Skip to content

Commit 71c0a82

Browse files
authored
Create Add Two Numbers II.py
1 parent d505a98 commit 71c0a82

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Add Two Numbers II.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
3+
4+
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
5+
6+
Follow up:
7+
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
8+
9+
Example:
10+
11+
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
12+
Output: 7 -> 8 -> 0 -> 7
13+
14+
'''
15+
16+
17+
# Definition for singly-linked list.
18+
# class ListNode(object):
19+
# def __init__(self, x):
20+
# self.val = x
21+
# self.next = None
22+
23+
class Solution(object):
24+
def addTwoNumbers(self, l1, l2):
25+
"""
26+
:type l1: ListNode
27+
:type l2: ListNode
28+
:rtype: ListNode
29+
"""
30+
a = 0
31+
while l1:
32+
a = a * 10 + l1.val
33+
l1 = l1.next
34+
35+
b = 0
36+
while l2:
37+
b = b* 10 + l2.val
38+
l2 = l2.next
39+
40+
digits = str(a + b)
41+
42+
dummy = ListNode(0)
43+
cur = dummy
44+
for x in digits:
45+
node = ListNode(int(x))
46+
cur.next = node
47+
cur = cur.next
48+
49+
return dummy.next

0 commit comments

Comments
 (0)