题目地址:https://leetcode.com/problems/factorial-trailing-zeroes/
public class FactorialTrailingZeroes_172 {
/**
* 5出现的次数比2多
*
* 5 2 -> 10
* 25 4 -> 100
* 125 8 -> 1000
* 625 16 -> 10000
*
* http://www.cnblogs.com/Lyush/archive/2012/08/06/2624549.html
*/
public int trailingZeroes(int n) {
int zeros=0;
int five=5;
while(n>=five){
zeros+=n/five;
if(five>Integer.MAX_VALUE/5)
break;
five*=5;
}
return zeros;
}
}
本文介绍了一种高效计算阶乘中尾随零数量的方法。通过分析2和5的配对关系,利用循环结构计算出给定整数n!(n的阶乘)结果末尾有多少个连续的0。该算法避免了直接计算阶乘所带来的巨大开销。
729

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



