1023. 阶乘零函数的个数
令f(x) 为x!的末尾0的个数。(回顾一下:x! = 1 * 2 * 3 * ... * x,并且我们规定0! = 1)
例如,f(3) = 0 因为 3! = 6 在末尾没有0,而 f(11) = 2 因为 11! = 39916800 在末尾有两个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]的整数.
public class Solution {
/**
* @param K: an integer
* @return: how many non-negative integers x have the property that f(x) = K
*/
public int preimageSizeFZF(int K) {
// Write your code here
long n = 1;
while (count(n) < K) {
n *= 5;
}
long left = 0;
long right = n;
while (left <= right) {
long mid = (left + right)/2;
if (count(mid) < K) {
left = mid + 1;
} else if (count(mid) > K) {
right = mid - 1;
} else {
break;
}
}
return left <= right ? 5 : 0;
}
long count(long n) {
long s = 0;
while (n != 0) {
n = n / 5;
s += n;
}
return s;
}
}