您的位置:首页 > 其它

《Cracking the Coding Interview》——第17章:普通题——题目3

2014-04-28 22:22 393 查看
2014-04-28 22:18

题目:计算N的阶乘尾巴上有多少个零?

解法:计算5的个数即可,因为2 * 5 = 10,2的个数肯定比5多。计算5的个数可以在对数时间内搞定。

代码:

// 17.3 Count how many zeros are there in n!?
// Count the number of 5s in n!.
#include <cstdio>
using namespace std;

int countZero(int n)
{
int res = 0;

while (n > 0) {
res += n / 5;
n /= 5;
}

return res;
}

int main()
{
int n;

while (scanf("%d", &n) == 1) {
printf("%d\n", countZero(n));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐