-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Two Numbers
More file actions
122 lines (88 loc) · 3.37 KB
/
Copy pathAdd Two Numbers
File metadata and controls
122 lines (88 loc) · 3.37 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
c1 = 0 # length of node 1
c2 = 0 #length of node 2
temp1 = l1
temp2 = l2
# n1 = []
# n2 = []
while temp1!= None:
c1+=1
# n1.append(temp1.val)
temp1 = temp1.next
while temp2!=None:
c2+=1
# n2.append(temp2.val)
temp2 = temp2.next
# print(c1,c2,n1,n2)
carry =0
temp1 = l1
temp2 = l2
while temp1!=None and temp2!=None:
if c1 <= c2 :
if temp2.val + temp1.val + carry < 10:
temp2.val = temp1.val + temp2.val + carry
carry = 0
else:
temp = temp1.val + temp2.val + carry
temp2.val = (temp1.val + temp2.val + carry)%10
carry = temp//10
# print(temp,carry)
else:
# print(temp2.val + temp1.val + carry)
if temp2.val + temp1.val + carry < 10:
temp1.val = temp1.val + temp2.val + carry
carry = 0
else:
temp = temp1.val + temp2.val + carry
temp1.val = (temp1.val + temp2.val + carry)%10
carry = temp//10
temp1 = temp1.next
temp2 = temp2.next
# temp2 = l2
# while temp2!=None:
# # c2+=1
# # n2.append(temp2.val)
# print(temp2.val)
# temp2 = temp2.next
if c1 <= c2:
# if c1 == c2:
# if carry!=0:
# newnode = ListNode(carry,None)
# temp2.next = newnode
# else:
while temp2!=None:
temp = temp2.val + carry
temp2.val = (temp2.val + carry)%10
carry = temp//10
temp2= temp2.next
else:
while temp1!=None:
temp = temp1.val + carry
print(carry , temp)
temp1.val = (temp1.val + carry)%10
carry = temp//10
temp1= temp1.next
print(carry)
if carry!=0:
if c1<=c2:
newnode = ListNode(carry,None)
temp2 = l2
while temp2.next!=None:
temp2= temp2.next
temp2.next = newnode
else:
newnode = ListNode(carry,None)
temp1 = l1
while temp1.next!=None:
temp1= temp1.next
temp1.next = newnode
if c1<=c2:
return l2
else:
return l1