LintCode: 尾部的零

问题:要求得到阶乘结果尾部的零,如11! = 39916800,尾部的零有2个。

分析:

当乘以5的倍数时,如5、10、15、25...,末尾会出现零,所以问题转换为阶乘过程中碰到了多少个5的倍数。比如:11!有两个5的倍数,一个是5,一个是10。

如果这样就结束的话,就太天真了。我们考虑另一种情况,25=5x5,25有两个5!125=5x5x5,125有三个5!所以,除了计算5的倍数外,还要考虑除以5后是否还能再除以5,(◎﹏◎)。

代码:

递归解法:

public class Solution {
    /*
     * @param n: An integer
     * @return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        // write your code here, try to do it without arithmetic operators.
        if (n == 0)
            return 0;
        else
            return n / 5 + trailingZeros(n / 5);
    }
}
循环解法:

public class Solution {
    /*
     * @param n: An integer
     * @return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        // write your code here, try to do it without arithmetic operators.
        long sum = 0;
        while (n != 0) {
            sum += (n / 5);
            n /= 5;
        }
        return sum;
    }
}

百度知道上看到的2015阶乘末尾有几个零的解答,可以提供点思路:

2015/5+2015/25+2015/125+2015/625=502

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值