-
Notifications
You must be signed in to change notification settings - Fork 0
/
q2_Add_Two_Numbers.py
57 lines (47 loc) · 1.28 KB
/
q2_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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# def print(self):
# a=self
# while a:
# print(a.val, end="")
# a=a.next
# print()
#
# def reverseList(self):
# L = ListNode(None)
# while self:
# L.next, self.next, self = self, L.next, self.next
# # a=self ; b=L.next ; c=self.next
# # L.next = self
# # self.next = b #Here,L.next=b
# # self = c
# return L.next
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
l3 = l4 = ListNode(0) #add=l3=l4
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
carry, val = divmod(carry,10)
l3.next = ListNode(val) #add.next=l3.next
l3 = l3.next #add=add.next
return l4.next
# l1 = ListNode(3)
# l1.next = ListNode(4)
# l2 = ListNode(5)
# l2.next = ListNode(6)
# s=Solution()
# s.addTwoNumbers(l1,l2).reverseList().print()