793. 阶乘函数后 K 个零

题目

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 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/preimage-size-of-factorial-zeroes-function
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

代码

class Solution {
    public int preimageSizeFZF(int k) {
// 左边界和右边界之差 + 1 就是答案
        return (int) (rightBound(k)-leftBound(k)+1);
    }

    public long trailingZeroes(long n) {//因为此函数单增,故可以用二分搜索
        long a=5,count=0;
        while (a<=n){
            count+=n/a;
            a*=5;
        }
        return count;
    }

    Long leftBound(int target){
        long low=0,high=Long.MAX_VALUE;
        while (low<high){
            long mid= low+(high-low)/2;
            if (trailingZeroes(mid)>=target) high=mid;
            else {
                low=mid+1;
            }

        }
        return low;
    }

    long rightBound(int target){
        long low=0,high=Long.MAX_VALUE;
        while (low<high){
            long mid= low+(high-low)/2;
            if (trailingZeroes(mid)<=target) low=mid+1;
            else {
                high=mid;
            }

        }
        return low-1;
    }
}

要点

  • 首先需要高效求解出n!的末尾有几个0的方法,
  • 然后根据这个方法单调递增的特性,再加入二分搜索确定左右端点
  • 最后计算出区间大小+1即为答案
  • 注意为了避免整型溢出的问题,trailingZeroes 函数需要把所有数据类型改成 long:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值