题目
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: