LeetCode 793. 阶乘函数后K个零 Python

f(x) 是 x! 末尾是0的数量。(回想一下 x! = 1 * 2 * 3 * ... * x,且0! = 1

例如, f(3) = 0 ,因为3! = 6的末尾没有0;而 f(11) = 2 ,因为11!= 39916800末端有2个0。给定 K,找出多少个非负整数x ,有 f(x) = K 的性质。

示例 1:
输入:K = 0
输出:5
解释: 0!, 1!, 2!, 3!, and 4! 均符合 K = 0 的条件。

示例 2:
输入:K = 5
输出:0
解释:没有匹配到这样的 x!,符合K = 5 的条件

注意:

  • K是范围在 [0, 10^9] 的整数

class Solution:
    def preimageSizeFZF(self,K):
        def CountZero(num):
            res = 0
            while num > 0:
                num //= 5
                res += num
            return res
        large, small = 5 * K + 5, 4 * K#首先找到上下界
        middle = (large+small) // 2
        while CountZero(middle) != K and large - small > 1:#此处是为了确保middle能在范围里面
            if CountZero(middle) > K:large = middle
            else: small = middle
            middle = (large+small) // 2
        
        middle1 = middle
        while CountZero(large) != K and large - middle1 > 1:
            temp = (middle1+large)//2
            if CountZero(temp) > K: large = temp
            else: middle1 = temp        
        
        while CountZero(large) != K and large >= small: large -= 1
        while CountZero(small) != K and small <= large: small += 1
        if CountZero(small) != K: return 0
        return large - small + 1

 

你可能感兴趣的:(LeetCode)