My Accepted Python Solution


  • 0
    B

    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)
            while l1.next:
                l1 = l1.next
                num1 = num1 + str(l1.val)
            while l2.next:
                l2 = l2.next
                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 currentTail.next: #while current node has next
                        currentTail = currentTail.next #change tail to its next node
                    currentTail.next = ListNode(int(c)) #change tail to next digit
                return head #finally return the linkedlist
            else:
                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.