-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Two Numbers.py
More file actions
56 lines (54 loc) · 1.38 KB
/
Copy pathAdd Two Numbers.py
File metadata and controls
56 lines (54 loc) · 1.38 KB
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
class ListNode: # Definition for singly-linked list.
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
if l1==None:
return l2
if l2==None:
return l1
n=ListNode(0)
m=n
flag=0
while l1 and l2:
m.next = ListNode((l1.val + l2.val + flag) % 10)
flag = (l1.val+l2.val+flag)//10
l2=l2.next
l1 = l1.next
m=m.next
if l1 :
while l1:
m.next =ListNode((l1.val + flag) % 10)
flag = (l1.val + flag) // 10
l1 = l1.next
m = m.next
if l2 :
while l2:
m.next = ListNode((l2.val +flag)%10)
flag=(l2.val+flag)//10
l2=l2.next
m=m.next
if flag==1:
m.next=ListNode(1)
return n.next
if __name__=='__main__':
a=ListNode(0)
b=a
for i in [2,4,3]:
b.next=ListNode(i)
b=b.next
l1=a.next
a=ListNode(0)
b=a
for i in [5,6,4]:
b.next=ListNode(i)
b=b.next
l2=a.next
solution=Solution()
n=solution.addTwoNumbers(l1,l2)
outnum=[]
while n:
outnum.append(n.val)
n=n.next
print(outnum)