[leetcode-172]Factorial Trailing Zeroes (c)

来源:互联网 发布:无线来源 我的淘宝 编辑:程序博客网 时间:2024/06/06 02:25

问题描述:
Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.
分析:问题说的很清楚,就是n!后面有多少零。那我们知道能够产生0的只有5和2,而将式子作分解的话,很清楚的知道5的个数一定比2的个数少。所以问题的关键就变成了n!里面有多少个5,我们知道小于n的5的个数有n/5个,但是这还不够,因为比如25是包含着2个5的。所以问题就变成了5的倍数+25的倍数+125的倍数。那同理,就变成了n/5,n/5/5, n/5/5/5的个数之和。

代码如下:4ms

int trailingZeroes(int n) {    int count = 0;    while(n){        n /=5;        count+=n;    }    return count;}
0 0