Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Solutions:
n!可以分解为n!=2x*3y*5z*....。可以得知结果中0的个数取决于5z*。
(1,n)的数中可以被5整除的有[n/5]个。
要注意的是25=5×5,出现一次就多了2个0,但计算的时候不会cnt += 2×[n/25],因为5已经计算过一次。只需加1.
class Solution {
public:
int trailingZeroes(int n){
if(n <= 1) {
return 0;
}
int cnt=0, base=5;
while(base <= n) {
cnt += n/base;
base *= 5;
}
return cnt;
}
};
但是在LC上超时。
(1,n)有多少能整除125的相当于n/5有多少能整除5的。执行通过。
class Solution {
public:
int trailingZeroes(int n){
if(n <= 1) {
return 0;
}
int cnt=0;
while(n > 0) {
cnt += n/5;
n /= 5;
}
return cnt;
}
};