leetcode 172. Factorial Trailing Zeroes(C语言,阶乘中尾数0的个数)26

贴原题:

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 creatingall test cases.

解析:
  本题是要计算一个数n的阶乘中尾部部分有多少个连续的0,所谓的trailing zeroes。
  按照leetcode的尿性,中规中矩地算阶乘,然后再慢慢腾腾地算尾部的0,且不说阶乘可能会越界,但这么算百分百会超出时间限制。
  那么其实,我们只需要考虑到2*5=10,而且2的倍数肯定多于5的倍数,所以我们只需要考虑n中包含多少个5的倍数就可以了。但另外比如25,是可以表示为5×5,即可以算作两个5,所以我们在做计算的时候要继续往下除以5。n/5/5/5……直到除到这个数小于5为止。

贴代码:
第一种方法:(本方法在最后一个测试用例时间超出,运行时间大概在1500ms)

int trailingZeroes(int n) {
    int cnt=0;//计数器
    for(int i=5; i<=n; i+=5)//只考虑5的倍数
    {
        cnt+=i/5;
        int n=i;
        while(n%5==0)//判断该数包含多少个5
        {
            cnt++;
            n/=5;
        }
    }
    return cnt;
}

第二种方法:(提交后显示的运行时间好像是3ms)

int trailingZeroes(int n) {
    int cnt=0;//计数器
    while(n)
    {
        n/=5;//计算包含多少个5
        cnt+=n;
    }
    return cnt;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值