https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
因为 2×5会导致结尾多一个0,所以这道题本质是算 5 的个数,因为2的个数总是大于5的个数。注意,25这样的是算两个5。
另外,注意,不断增大除数的效率没有不断减小被除数的效率高,虽然结果是一样的,下面我被注释掉的代码是过不了大数的。
public int trailingZeroes(int n) {
if(n<=0) return 0;
int count = 0;
while(n>0){
count+=n/5;
n = n/5;
}
// for(int i=5; i<=n; i*=5){
// count+=n/i;
// }
return count;
}
本文介绍了一种计算阶乘结果中尾部零数量的方法,利用除以5的次数来得出答案,优化了大数处理效率。
265

被折叠的 条评论
为什么被折叠?



