leetcode 172. Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

题意是计算n!的末尾的0的个数。要求运行时间为对数时间。

先给出最直接的思路:先计算出n! , 然后用n%10依次抽取出末位,并判断是不是0,一旦出现非0则停止计数。显然该方法不满足对数时间要求,且在n=13的时候会内存溢出。

class Solution {
public:
    int trailingZeroes(int n) {
    int q = 1, ans = 0,count=0;
    for (int i = 2; i <= n; ++i)
    {
        ans = q*i;
        q = ans;
    }
    while (ans)
    {
        if (!(ans % 10))
            ++count;
        ans /= 10;
        if (ans%10)
            break;
    }  
    return count;
    }
};

下面思考如何避免直接求出 n! 。可以发现 0 的出现都是由于质数2和5相乘, 理论上统计出对 1:n 进行质因子分解,分别得出2和5的总个数为a,b,取min(a,b)即是0的个数,显然 min(a,b)=b,即5的个数。5的个数可用 floor(n/5) 得到。同时考虑到 25 有 2 个 5 , 125 有 3 个 5,… , 故要对(n/5)进行迭代,直到为 0 。

class Solution {
public:
    int trailingZeroes(int n) {
    int ans=0;
    while(n){
        n/=5;
        ans+=n;
    }
    return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值