首页 > 代码库 > 【LeetCode】Factorial Trailing Zeroes (2 solutions)

【LeetCode】Factorial Trailing Zeroes (2 solutions)

Factorial Trailing Zeroes

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!做质因数分解n!=2x*3y*5z*...

显然0的个数等于min(x,z),并且min(x,z)==z

解法一:

从1到n中提取所有的5

class Solution {public:    int trailingZeroes(int n) {        int ret = 0;        for(int i = 1; i <= n; i ++)        {            int tmp = i;            while(tmp%5 == 0)            {                ret ++;                tmp /= 5;            }        }        return ret;    }};

技术分享

 

解法二:

由上述分析可以看出,起作用的只有被5整除的那些数。能不能只对这些数进行计数呢?

存在这样的规律:[n/k]代表1~n中能被k整除的个数。

因此解法一可以转化为解法二

class Solution {public:    int trailingZeroes(int n) {        int ret = 0;        while(n)        {            ret += n/5;            n /= 5;        }        return ret;    }};

技术分享

【LeetCode】Factorial Trailing Zeroes (2 solutions)