设计一个算法,计算出n阶乘中尾部零的个数
样例
11! = 39916800,因此应该返回 2
挑战
果然简单易懂了不少。
O(logN)的时间复杂度
自然的就想到产生0的有2*5一个0,4*25两个0,8*125三个0,所以只需要算有多少能整除5及5的次方数,再根据这个算阶乘最后0的数目,所以自己写出来的代码是这样
class Solution {
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
write your code here
long ans = 0;
long i = 0;
while((long)Math.pow(5,i) <= n){
i++;
}
for(long j = 1; j < i; j++){
ans+=n/((long)Math.pow(5,j));
}
return ans;
}
};
然后搜了一下发现不用这么麻烦,因为4*25本质也是可以看作2*5*2*5,所以只需要对第一次整除5后的数继续整除5,直到除不尽。所以代码变成了
class Solution {
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
long ans = 0;
while(n > 0){
ans += n/5;
n/=5;
}
return ans;
}
};
果然简单易懂了不少。