[LeetCode] #172 阶乘后的零

给定一个整数 n,返回 n! 结果尾数中零的数量。

输入: 5

输出: 1

解释: 5! = 120, 尾数中有 1 个零.

思路一:

先求阶层,再计算零的数量

该方法速度慢,且需要防溢出

import java.math.BigInteger;

public int trailingZeroes(int n) {

    BigInteger nFactorial = BigInteger.ONE;
    for (int i = 2; i <= n; i++) {
        nFactorial = nFactorial.multiply(BigInteger.valueOf(i));
    }
                    
    int zeroCount = 0;
    
    while (nFactorial.mod(BigInteger.TEN).equals(BigInteger.ZERO)) {
        nFactorial = nFactorial.divide(BigInteger.TEN);
        zeroCount++;
    }
    
    return zeroCount;
}

思路二:

以5! = 120为例,5! = 1*2*3*4*5

出现1个0是因为有一对2*5

以10! = 3628800为例,10! = 1*2*3*4*5*6*7*8*9*10

出现2个0是因为有一对2*5和10

由此可以看出每隔5个数就会出现5或5的倍数,而0的数量正是由5的数量决定

所以我们从1到n计算其中5的数量,但该方法同样速度慢

public int trailingZeroes(int n) {
    int count = 0;
    for (int i = 1; i <= n; i++) {
        int N = i;
        while (N > 0) {
            if (N % 5 == 0) {
                count++;
                N /= 5;
            } else {
                break;
            }
        }
    }
    return count;

}

思路三:

以25!为例,25! = 1*...5...10...15...20...25 = 1*...5...2*5...3*5...4*5...5*5

可以看出每隔5个数就出现一个5,每隔25个数出现两个5,以此类推 每隔125个数出现三个5...

n/5可以计算出“隔5个数出现的5”,n/25可以计算出“隔25个数出现的5”...

所以最终5的个数是n/5+n/25+n/125...

class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        while (n > 0) {
            n /= 5;
            count += n;
        }
        return count;
    }
}

知识点:

BigInteger:BigInteger详解

总结:不一定需要在结果中找答案,有的时候,在过程中也可以找到答案

posted @ 2021-08-27 13:42  1243741754  阅读(37)  评论(0编辑  收藏  举报