LeetCode[Math]: Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

这个题目参考了Simple C/C++ Solution (with detailed explaination)My one-line solutions in 3 languages这两个discuss。

思路就是:0是从10来的,10是从2x5来的,2总是充足的,所以只需要计算5的个数就行了,但是要注意5x5=25、5x5x5=125···

详细解释可参见第一个discuss,讲的挺详细的。

C++代码如下:

int trailingZeroes(int n) {
    int result = 0;
    for(long long i = 5; n / i > 0; i *= 5) {
        result += (n / i);
    }

    return result;
}

第二个讨论原理与上同,但是用递归的方法只用一行代码就解决了这个问题,在此也MARK一下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值