8 Python lines recursive solution


  • 0
    H
    class Solution(object):
        def addTwoNumbers(self, l1, l2, carry=0):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if not l1 and not l2:
                return None if not carry else ListNode(1)
            l1 = l1 or ListNode(0)
            l2 = l2 or ListNode(0)
            value = l1.val + l2.val + carry
            carry = 1 if value > 9 else 0
            node = ListNode(value % 10)
            node.next = self.addTwoNumbers(l1.next, l2.next, carry=carry)
            return node
    

Log in to reply
 

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