算法-----一个数的阶乘结果尾部零的个数
题目:设计一个算法,计算出n阶乘中尾部零的个数
样例 11! = 39916800,因此应该返回 2
题目链接:http://www.lintcode.com/problem/trailing-zeros
算法分析:
只有2*5才能得出一个0,所以其实就是找从1到n的所有(2,5)对。又因为2的个数多于5的个数,所以尾部有多少0取决于5的个数。看到的公式:count+=n/5^i.其中5^i小于n。完整代码如下所示:
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 m=1;
// for(int i=1;i<=n;i++){
// m=m*i;
// }
// long num=0;
// while(m%10==0){
// num++;
// m/=10;
// }
// return num;
long num=0;
for(int i=1;Math.pow(5,i)<n;i++){
num+=n/(long)Math.pow(5,i);
}
return num;
}
};

浙公网安备 33010602011771号