Dumbo
Dumbo

Reputation: 1098

leetcode problem, works on testcode, but marked wrong

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

Answers (1)

Akshat
Akshat

Reputation: 185

  1. You are not adding carry to the value for the case when one of the list ends. Consider for eg:
    [9,2]
    [1]
    Here, after adding 1 and 9, value is 0 and carry is 1. Now, l2 terminates, so in loop of l1, you need to add carry to value val=(l1.val+carry)%10
  2. Also, the case where both l1 and l2 terminate, carry needs to be added. Consider for eg:
    [9,9]
    [1]
    Here, after adding we get [0,0] but both l1,l2 terminate so a new node with carry needs to be created after the while loop.

Upvotes: 1

Related Questions