您的位置:首页 > 其它

LintCode 第二题 计算阶乘结果尾部的零

2018-03-01 21:46 309 查看

解法1 硬算(失败)

判断一个数的尾数有多少个零,显然最笨的方法就是依次除以10,100,1000…取余,只要余数为0,则尾部零的的个数加一,直到不为0循环跳出。如果这样计算的话显然与题目”阶乘”不大相符,而且如果阶乘数大的话,会无法存储。

解法2 分析”5 25 125 …”出现的次数

参考链接:http://blog.csdn.net/zyh2525246/article/details/53697136

具体分析可以见参考链接,阶乘尾数零的个数为5,25,125..倍数个数的和。

如果是求2016!后面0的个数呢?

5的倍数个数为: 2016/5 = 403个

25的倍数个数为: 403/5 = 80个

125的倍数的个数为:

80/5 = 16个

625的倍数的个数为: 16/5 = 3个

所以可以得出2016!后面0的个数为:403+80+16+3 = 502个

实现代码如下:

public class Solution {
/*
* @param n: An integer
* @return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here, try to do it without arithmetic operators.

long result = 0;
while(n > 0) {
result += n / 5;
n /= 5;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: