Local run is fine for my non-recursive solution but failed online


  • 0
    J

    My local run seems to be fine and it's supposed to be non-recursive solution. I'm not sure why it always shows "time limit exceed" for my non-recursive solution below.

    class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        result = None
        addon = 0
        prev = result
        head = None
        while l1 != None or l2 != None:
            total = addon
            if l1 != None:
                total+=l1.val
            if l2 != None:
                total+=l2.val
            if total == 0:
                break
            result = ListNode(total%10)
            addon = int(total/10)
            if prev != None:
                prev.next = result
            prev = result
            if head == None:
                head = result
            if l1 != None:
                l1 = l1.next
            if l2 != None:
                l2 = l2.next
        if addon > 0:
            result.next = ListNode(addon)
        return head

  • 0
    J

    I finally figure out that following piece,

    int(total/10)
    

    will somehow let OJ's test run exceed time limit. Change it to following way would fix the issue.

    (total/10)

Log in to reply
 

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