首页 > 其他 > 详细

【LeetCode】Factorial Trailing Zeroes (2 solutions)

时间:2014-12-30 13:26:36      阅读:325      评论:0      收藏:0      [点我收藏+]

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)

原文:http://www.cnblogs.com/ganganloveu/p/4193373.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!