您的位置:首页 > 大数据 > 人工智能

LeetCode172:Factorial Trailing Zeroes

2015-06-07 15:09 369 查看
Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.


这道题需要在对数时间内求解阶乘中尾端0的个数。

阶乘中0的个数是由各项因子中2和5的个数决定的,又由于阶乘是连续n的数的积,所以2的数目比5的数目多,故0的个数就等于各项因子中5的个数。

以10!为例分析:

10!=10*9*8*7*6*5*4*3*2*1

包含因子2的数有5个,10=2*5,8=2*4,6=2*3,4=2*2,2=2*1

其中除以2后剩下的5个数分别为5,4,3,2,1,依然存在包含2的数为4,2,

除以2后依然存在一个包含2的数2

这样10!中包含2的个数是【10/2】+【10/2^2】+【10/2^3】=5+2+1

注:【num】表示不大于num的最大的整数

也可以用同样的方式求5的因子的个数,而这道题就是求5的因子的个数。

runtime:3ms

class Solution {
public:
    int trailingZeroes(int n) {
        int result=0;
        while(n>=5)
        {
            result+=n/5;
            n/=5;
        }
        return result;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: