Python


  • 0
    T
    def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            i = l1
            j = l2
            
            carry = 0
            answer = []
            while i is not None and j is not None:
                current_sum = i.val + j.val + carry
                if current_sum >= 10:
                    carry = 1
                    answer.append(current_sum - 10)
                elif current_sum < 10:
                    carry = 0
                    answer.append(current_sum)
                i = i.next
                j = j.next
            
            longer = None
            if i is not None:
                longer = i
            elif j is not None:
                longer = j
            else:
                if carry == 0: return answer
                answer.append(carry)
                return answer
                
            while longer is not None:
                current_sum = longer.val + carry
                if current_sum >= 10:
                    carry = 1
                    answer.append(current_sum - 10)
                elif current_sum < 10:
                    carry = 0
                    answer.append(current_sum)
                longer = longer.next
                
            if carry == 0: return answer
            answer.append(carry)
            return answer
    

    When adding two single digit numbers, 2 things can happen, the numbers sum to less than 10 or the numbers are greater than or equal to 10. If the sum is less than 10, you can add the number to the result as is. However if the number is greater than 10 you have a carry. The carry will always be 1 or 0 because the maximum number that can be formed from two single digit numbers is 18, so at most in one computation you can have 19. You must always add the carry in the computation, so in reality what you are checking is if whether a digit from the first list plus a digit from the second list plus carry is greater than or less than 10.

    One number may be longer than the other. In a linked list you can determine which number it is by checking which pointer is none. From this pointer onward you add the value plus any corresponding carries.

    If the number is the same length, you may still end up with a carry. Therefore you have to explicitly check for that.


  • 0
    O

    The answer requires to return a Linked List but your answer is a list.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.