106ms Python solution


  • 0
    M
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            head = hasHead = False
            c = 0
            
            while l1 != None or l2 != None:
                if hasHead == False:
                    tail = head = ListNode(c)
                    tmp = ListNode(0)
                else:
                    tmp = ListNode(c)
                    tail.next = tmp
                    tail = tmp
                if l1 != None:
                    if hasHead:
                        tmp.val += l1.val
                    else:
                        head.val += l1.val
                    l1 = l1.next
                if l2 != None:
                    if hasHead:
                        tmp.val += l2.val
                    else:
                        head.val += l2.val
                    l2 = l2.next
                c = tail.val / 10
                tail.val %= 10
                hasHead = True
                
            if c != 0:
                tail.next = ListNode(c)
            return head
    

    No algorithm inside. Not smart either but somehow effective.


Log in to reply
 

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