2999. Count the Number of Powerful Integers

2999. Count the Number of Powerful Integers

class Solution:
    def numberOfPowerfulInt(self, start: int, finish: int, l: int, s: str) -> int:
        cnt=[0]*16
        def count(n):
            res,i,sz=cnt[len(n)-1],0,len(n)-len(s)
            while True:
                res += n[i:]>=s if i==sz else cnt[len(n)-i-1]*(min(l,int(n[i])-1)+(i>0))
                i+=1
                if i>sz or int(n[i-1])>l:
                    break
            return res


        for i in range(len(s),16):
            cnt[i]=1 if i==len(s) else cnt[i-1]*(l+1)
        
        return count(str(finish))-count(str(start-1))

这里cnt表示的后一位的情况

1)首先考虑终止情况,此时最多有一种就是当所有位是exactly s

2) 其次,对于一般情况,

这里n[i]-1是因为当前位的最大值不能控制后面几位的情况

(i>0)是要首位不为0

int(n[i-1])>l此时cnt 完全取到了上限

你可能感兴趣的:(leetcode)