Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
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.
My solution:
# 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
"""
add_before=0
count=0
while l1.next!=None and l2.next!=None:
value1=l1.val
value2=l2.val
value=value1+value2+add_before
if value>=10:
value=value-10
add_before=1
else:
add_before=0
if count==0:
start_node=ListNode(value)
tmp_node=start_node
else:
tmp1_node=ListNode(value)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
count+=1
l1=l1.next
l2=l2.next
#Special occasion for last digit
value1=l1.val
value2=l2.val
value=value1+value2+add_before
if value>=10:
value=value-10
add_before=1
else:
add_before=0
if count==0:
start_node=ListNode(value)
tmp_node=start_node
else:
tmp1_node=ListNode(value)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
if add_before==1 and l1.next==None and l2.next==None:
tmp1_node=ListNode(add_before)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
if l1.next==None and l2.next==None:
return start_node
if l1.next==None:
l_temp=l2
elif l2.next==None:
l_temp=l1
l_temp=l_temp.next
while l_temp.next!=None:
value=l_temp.val
value=value+add_before
if value>=10:
add_before=1
value=value-10
else:
add_before=0
tmp1_node=ListNode(value)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
l_temp=l_temp.next
value=l_temp.val
value=value+add_before
if value>=10:
value=value-10
add_before=1
else:
add_before=0
tmp1_node=ListNode(value)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
if add_before==1:
tmp1_node=ListNode(add_before)
tmp_node.next=tmp1_node
tmp_node=tmp1_node
return start_node
Solution:
https://leetcode.com/problems/add-two-numbers/solution/