0

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)

1 Answer 1

1
  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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.