算法 | Leetcode 172 阶乘后的零

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

示例 1:

输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:

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

题解:
    class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        //判断5的数量即可
        while(n >= 5) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
    //本来想用递归做的,在leetcode会超时
    // public int trailingZeroes(int n) {
    //     if(n<=1) return 0;
    //     return trailingZeroes(n-1)+zeroNums(n);
    // }
    // private int zeroNums(int n){
    //     int sum = 0;
    //     while(n%5==0){
    //         n/=5;
    //         sum++;
    //     }
    //     return sum;
    // }
}

猜你喜欢

转载自blog.csdn.net/CYK5201995/article/details/106420770