My Accepted Python Solution

  • 0

    Description: Iterate through both lists and append each digit of from lists into separate strings (num1 and num2). Reverse those strings and add the numbers up. Reverse the sum and then iteratively add each digit of the reversed sum to the linkedlist. Finally, return the first node of the linkedlist.

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            num1 = str(l1.val)
            num2 = str(l2.val)
                l1 =
                num1 = num1 + str(l1.val)
                l2 =
                num2 = num2 + str(l2.val)
            num1 = num1[::-1]
            num2 = num2[::-1]
            sumVal = int(num1)+int(num2)
            sumStr = str(sumVal)
            sumStr = sumStr[::-1]
            if(len(sumStr) > 1):
                head = ListNode(int(sumStr[0:1]))
                currentTail = head
                for c in sumStr[1:]:
                    while #while current node has next
                        currentTail = #change tail to its next node
           = ListNode(int(c)) #change tail to next digit
                return head #finally return the linkedlist
                return ListNode(int(sumStr)) #return linkedlist with single node

Log in to reply

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