-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd_Two_Numbers.py
83 lines (68 loc) · 1.58 KB
/
Add_Two_Numbers.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
You are given two linked lists representing two non-negative numbers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
# base cases
if l1 == None and l2 == None:
return None
if l1 == None:
return l2
if l2 == None:
return l1
n1 = l1
n2 = l2
carry = 0
result = ListNode(-1)
pointer = result
while n1 != None or n2 != None or carry != 0:
a = n1.val if n1 != None else 0
b = n2.val if n2 != None else 0
total = a + b + carry
remainder = total % 10
carry = total / 10
sum_node = ListNode(remainder)
pointer.next = sum_node
pointer = pointer.next
if n1 != None:
n1 = n1.next
if n2 != None:
n2 = n2.next
return result.next
#### Testing ####
def printList(self, head, size=100):
pointer = head
s = ""
counter = 0
while pointer != None and counter < size:
s = s + str(pointer.val) + " , "
pointer = pointer.next
counter = counter + 1
print s
s = Solution()
l1 = ListNode(9)
pointer = l1
for i in range(2,3,1):
temp = ListNode(i)
pointer.next = temp
pointer = pointer.next
l2 = ListNode(1)
pointer = l2
for i in range(2,3,1):
temp = ListNode(9)
pointer.next = temp
pointer = pointer.next
x = s.addTwoNumbers(l1, l2)
s.printList(l1)
s.printList(l2)
s.printList(x)