码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Factorial Trailing Zeroes (2 solutions)

时间:2014-12-30 13:28:46      阅读:141      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!