Iterative Python code beats 99.29% python submission


  • 0
    Q
    class Solution(object):
        
        def firstTwo(self, n, zero):
            limit=2 if zero else (n-1)/2+1
            for i in xrange(1, limit):
                j=i+1
                while n-j>=max(i, j-i):
                    yield (i, j)
                    j+=1
            
        def isAdditiveNumber(self, num):
            n=len(num)
            for i, j in self.firstTwo(n, num[0]=="0"):
                if num[i]=="0" and j-i>1: continue
                a, b, cur=num[:i], num[i:j], j
                while True:
                    c=str(int(a)+int(b))
                    if num.startswith(c, cur):
                        cur+=len(c)
                        if cur==n: return True
                        a, b=b, c
                    else:
                        break
            return False
    

Log in to reply
 

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