python O(n), no extra space, using list <- -> num convertion

  • 0

    The idea is to convert linked list into number, get the sum and convert the number back to a linked list.

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            def listToNum(node, previous=0):
                if is None:
                    return previous * 10 + node.val
                return listToNum(, previous * 10 + node.val)
            def numToList(num):
                num, val = divmod(num, 10)
                node = ListNode(val)
                if num == 0:
                    return (node, node)
                first, last = numToList(num)
       = node
                return (first, node)
            n1, n2 = listToNum(l1), listToNum(l2)
            return numToList(n1 + n2)[0]

Log in to reply

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