Leetcode4: Factorial Trailing Zeroes

243 篇文章 0 订阅

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的阶乘末尾有多少个0。并且要求时间复杂度是logN。

分析:N的阶乘的末尾为0只可能是2*5的情况,所以分析N个数里面因子为2和5的个数就行,又因为因子有2的数一定大于因子有5的数目,所以可以只考虑N里面有多少个数的因子是5。但是会考虑到25里面5的因子贡献为2,125里面为3等等。1-N中包含5的数目是floor(N/5),包含25的数目是floor(N/25),我们需要注意到的是floor(N/5)里面其实包含了floor(N/25),所以其实最后的总数可以依下式计算:

sum = floor(N/5)+ floor(N/25)+ floor(N/125)+ ……

一种解法是:

class Solution {
public:
    int trailingZeroes(int n) {
        int sum = 0;
        int factor = 5;
        while(n >= factor)
        {
            sum = sum + n/factor;
            factor = factor * 5;
        }
        return sum;
    }
};

但是这种方法会报超时,这种方法是不断增大数据(除数),当数据很大时会超时,LZ对超时这种问题感到非常头疼 =。=

另一种解法:

class Solution {
public:
    int trailingZeroes(int n) {
        int sum = 0;
        while(n)
        {
            sum += n/5;
            n /= 5;
        }
        return sum;
    }
};
这种方法是数据不断减小,不会出现超时问题。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值