Python solution, 132ms


  • -1
    K

    To make it faster, use while l1 or l2 instead of while l1 and l2 + while l1 + while l2. h is dummy head.

    def addTwoNumbers(self, l1, l2):
        h = ListNode(0)
        p, carry = h, 0
        while l1 or l2:
            Sum = carry
            if l1:
                Sum, l1 = Sum + l1.val, l1.next
            if l2:
                Sum, l2 = Sum + l2.val, l2.next
            p.next, carry = ListNode(Sum % 10), Sum / 10
            p = p.next
        p.next = ListNode(carry) if carry else None
        return h.next

Log in to reply
 

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