Leetcode_2 Add Two Numbers [Medium] (Python)

Description

You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

Solution1

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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1==None and l2==None:
return None
if l1==None:
return l2
if l2==None:
return l1
q=ListNode(-1)
p=q
flag=0
p1=l1
p2=l2
while p1!=None and p2!=None:
temp=ListNode(p1.val+p2.val+flag)
if temp.val>=10:
temp.val=temp.val%10
flag=1
else:
flag=0
p.next=temp
p=p.next
if flag==1 and p1.next==None and p2.next==None:
t=ListNode(1)
p.next=t
p1=p1.next
p2=p2.next
while p1!=None:
p1.val=p1.val+flag
if p1.val>=10:
p1.val=p1.val%10
flag=1
else:
flag=0
p.next=p1
p=p.next
if flag==1 and p1.next==None:
t=ListNode(1)
p.next=t
break
p1=p1.next
while p2!=None:
p2.val=p2.val+flag
if p2.val>=10:
p2.val=p2.val%10
flag=1
else:
flag=0
p.next=p2
p=p.next
if flag==1 and p2.next==None:
t=ListNode(1)
p.next=t
break
p2=p2.next
return q.next

Solution2

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
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prev = None
head = l1
carry = 0
while l1 and l2:
n = l1.val + l2.val + carry
val, carry = n % 10, n // 10
l1.val = val
prev, l1, l2 =l1, l1.next, l2.next # Need prev after we finish the loop

l = l1 or l2
prev.next = l # to link the previous added list to the rest of the uncounted list (l1 or l2)

while l:
n = l.val + carry
val, carry = n % 10, n // 10
l.val = val
prev, l = l, l.next

# In case there is carry after last digit
if carry:
prev.next = ListNode(carry)

return head
-------------End of the articleThank you for reading-------------
  • Author of this article:zfish
  • Link to this article: archives/4b735f76.html
  • Copyright Notice: All articles in this blog, except for special statements, please indicate the source!
0%