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

猜你喜欢

转载自blog.csdn.net/cblstc/article/details/79125019
今日推荐