xinyu04

导航

LeetCode 793. Preimage Size of Factorial Zeroes Function 二分

Let f(x) be the number of zeroes at the end of x!. Recall that \(x! = 1 * 2 * 3 * ... * x\) and by convention, 0! = 1.

For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.
Given an integer k, return the number of non-negative integers x have the property that f(x) = k.

Solution

\(f(x)\) 表示的是后缀0的个数,现在给定这个数量,问有多少个 \(x\) 满足这个条件。我们可以用二分确定上下界范围 然后 \(right-left+1\) 就是满足条件的个数

点击查看代码
class Solution:
    def preimageSizeFZF(self, k: int) -> int:

        def count_zero(k):
            ans=0
            while int(k/5)>0:
                ans+=int(k/5)
                k=k/5
            return ans
        
        def left_bound(tgt):
            low = 0
            high = 2 ** 32
            while low<high:
                mid = low+int((high-low)/2)
                if count_zero(mid)<tgt:
                    low=mid+1
                elif count_zero(mid)==tgt:
                    high=mid
                elif count_zero(mid)>tgt:
                    high=mid
            return low
        
        def right_bound(tgt):
            low = 0
            high = 2 ** 32
            while low<high:
                mid = low+int((high-low)/2)
                if count_zero(mid)<tgt:
                    low=mid+1
                elif count_zero(mid)==tgt:
                    low=mid+1
                elif count_zero(mid)>tgt:
                    high=mid
            return low-1
        
        return right_bound(k)-left_bound(k)+1

posted on 2023-07-16 23:15  Blackzxy  阅读(4)  评论(0编辑  收藏  举报