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]
.
题目描述:设关于整数x的函数f(x),返回x!末尾0的个数,给定K,问使得f(x)=K的x有多少个
思路:
首先我们想到,要构成x!末尾的0,就需要因子中含有2和5,或者因子的因子含有2和5(例如4和15),因此要计算f(x),只需要计算1~x的因子中含有的2和5的个数;进一步想到,x至少增加5,才能使得因子5的个数增加,而x主要增加2,就会使得因子2的个数增加,所以对于任意的x,1~x中因子5的个数一定大于(或等于)因子2的个数,因此1~x中因子5的个数就是x!末尾0的个数;再继续想到,因为没5个数就一定会出现至少一对2和5,所以,对于任意的K,所求的解要么是0,要么是5,也就是说,如果存在x使得f(x)=K,那么,可能的x的个数就是5.
然后,要考虑如何验证是否存在x使得f(x)=K,因此我们需要找到一个这样的x,使得f(x)=K,考虑使用二分法,这里,由于LeetCode的用例设置的比较大,所以二分的上限需要设置的大一些。
然后,我们要思考的是如何计算1~x中因子5的个数,想到,每5个数就是增加一个因子5,每25个数会额外增加一个因子5,每625个数又会额外增加一个5,因此1~x中因子5的个数可以通过将x与5的幂的商相加得到。
class Solution {
public int preimageSizeFZF(int K) {
if(min(K))
return 5;
return 0;
}
public boolean min(int n){
long left = 0, right = Integer.MAX_VALUE;
right *= 100000;
while(left < right){
long mid = left + (right - left) / 2;
long count = 0;
long base = 5;
//System.out.println(mid);
while(base <= mid){
count += mid / base;
base *= 5;
}
if(count == n){
//System.out.println(mid + "!!");
return true;
}
if(count < n)
left = mid + 1;
else
right = mid - 1;
}
//System.out.println(left);
return false;
}
}