您的位置:首页 > 编程语言 > C语言/C++

LintCode 2.尾部的零 C++

2018-01-27 16:22 776 查看
LintCode 2.尾部的零 C++

问题描述:设计一个算法,计算出n阶乘中尾部零的个数

样例:11! = 39916800,因此应该返回
2

分析:把1×2×3×4×……×n中每一个数因式分解,会出现:
1×2×3×(2×2)×5×(2×3)×……
像这样。十进制数结尾的有多少个0,就表示其因数里有多少个10——其他进制也一样,一个M进制的数,让结尾多一个0就等价于乘以M。对于十进制来说,有多少个10,就意味着有多少个5(10=2×5,2有很多)
9123
。那么,我们可以循环统计可以整除5、25、125......的数,即可得出零的个数。

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

long long count = 0;
long long fiveTimes = 1;

while(fiveTimes * 5 <= n){
fiveTimes = fiveTimes * 5;
count += n / fiveTimes;
}
return count;
}
};代码借鉴:http://blog.csdn.net/hk_john/article/details/78806907
如有错误,请批评指出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: