A python solution, no idea how to improve it


  • 0
    C
    # 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
            """
            c = 0
            r = ListNode(0)
            cur = r
            while l1 or l2 or c == 1:
                if c == 0 and not (l1 and l2):
                    # if c is 0, and one of the list is run out, 
                    # we can stop here.
                    cur.next = l1 if l1 else l2
                    return r.next
                v1, v2 = 0, 0
                if l1: l1, v1 = l1.next, l1.val
                if l2: l2, v2 = l2.next, l2.val
                sum = v1 + v2 + c
                c = sum / 10
                sum = sum % 10
                cur.next = ListNode(sum)
                cur = cur.next
                
            return r.next
    

    It costs more than 100ms to finish, but I don't know how to improve it.
    It would be highly appreciated if anyone could give me some advice.
    Thank you!


Log in to reply
 

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