Python Imitation Solution


  • 0
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            ans = dummy = ListNode(-1)
            carry = 0
            while l1 or l2:
                if not l1:
                    carry, val = (l2.val + carry) / 10, (l2.val + carry) % 10
                    dummy.next = ListNode(val)
                    l2 = l2.next
                elif not l2:
                    carry, val = (l1.val + carry) / 10, (l1.val + carry) % 10
                    dummy.next = ListNode(val)
                    l1 = l1.next
                else:
                    carry, val = (l1.val + l2.val + carry) / 10, (l1.val + l2.val + carry) % 10
                    dummy.next = ListNode(val)
                    l1, l2 = l1.next, l2.next
                dummy = dummy.next
            val = None if not carry else ListNode(carry)
            dummy.next = val
            return ans.next
    

Log in to reply
 

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