Reputation: 1098
Here is the original problem: https://leetcode.com/problems/add-two-numbers/
My solution is marked wrong but it works on test-case and I don't see why. Could you pls see.
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ln = ListNode(0)
lll= ln
val=0
carry=0
while l1 or l2:
if l1 and l2:
val, carry = (l1.val+l2.val+carry)%10, (l1.val+l2.val+carry)/10
l1=l1.next
l2=l2.next
elif l2:
val, carry = l2.val%10, 0
l2=l2.next
elif l1:
val, carry = l1.val%10, l1.val/10
l1=l1.next
ln.val=val
if l1 or l2 or carry>0:
ln.next=ListNode(0)
ln=ln.next
return(lll)
Upvotes: 0
Views: 79
Reputation: 185
l2
terminates, so in loop of l1
, you need to add carry to value val=(l1.val+carry)%10
l1
and l2
terminate, carry needs to be added. Consider for eg:
l1,l2
terminate so a new node with carry needs to be created after the while loop.Upvotes: 1