100% Fastest Python Solution


  • 0
    C
    class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        counter = 1
        head = ListNode(None)
        
        while l1 or l2 or carry:
            
            sum = carry
            
            if l1:
                sum+= l1.val
                l1 = l1.next
            if l2:
                sum+=l2.val
                l2 = l2.next
    
            digit = sum%10
            carry = sum/10
            
            if counter == 1:
                head.val = digit
                node = head
            else:
                node.next = ListNode(digit)
                node = node.next
            
            counter += 1
            
        return head

  • 0
    L

    The if-else can be removed if you use an extra head node.

    ...
    head = ListNode(None)
    tail = head
    while ...:
        ...
        tail.next = ListNode(digit)
        tail = tail.next
    ...
    return head.next
    

  • 0
    O

    This is simpler:
    def addTwoNumbers(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    head=ListNode(0)
    temp=head
    carry=0
    while l1 or l2 or carry:
    if l1:
    carry+=l1.val
    l1=l1.next
    if l2:
    carry+=l2.val
    l2=l2.next
    temp.next=ListNode(carry%10)
    carry/=10
    temp=temp.next
    return head.next


  • -1
    L

    You are very lucky!


Log in to reply
 

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