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 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.

Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.

Note:

  • K will be an integer in the range [0, 10^9].
分析:如果用arr[i] 表示f(i)有多少个0的话,那么arr[i]数组是一个递增数组,这样就可以用二分查找。首先是如下函数,计算num!有多少个0、

为防止Integer溢出,都使用 long类型。

    private long getZerosCount(long num) {
        long count = 0;
        for (long i = 5; num / i >= 1; i *= 5) {
            count += num / i;
        }
        return count;
    }

因为每出现一个5,就会多一个0,。出现一个25就会多两个0,125三个0.。。。 所以只需要计算他们出现的次数即可,因为计算5的个数的时候,25已经计算过一次,所以下次计算只需要一次即可。

通过二分法去查找符合f(x)末尾的0的个数<=k的最大x。

    private long lessThanK(int K) {
        long low = 0, high = ((long) Integer.MAX_VALUE) * 10L;
        while (low < high) {
            long mid = low + (high - low + 1) / 2;
            long count = getZerosCount(mid);
            if (count <= K) low = mid;//int自动转long去比较
            else high = mid - 1;
        }
        return low + 1;
    }
最后的代码如下:

class Solution {
    public int preimageSizeFZF(int K) {
        if (K == 0) return 5;
        else return (int) (lessThanK(K) - lessThanK(K - 1));
    }

    private long lessThanK(int K) {
        long low = 0, high = ((long) Integer.MAX_VALUE) * 10L;
        while (low < high) {
            long mid = low + (high - low + 1) / 2;
            long count = getZerosCount(mid);
            if (count <= K) low = mid;//int自动转long去比较
            else high = mid - 1;
        }
        return low + 1;
    }

    private long getZerosCount(long num) {
        long count = 0;
        for (long i = 5; num / i >= 1; i *= 5) {
            count += num / i;
        }
        return count;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值