zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode_阶乘尾数中0的个数

2023-04-18 16:11:11 时间

LeetCode,随机一题。

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

题目解析:

主要问题为阶乘后的值过大,通过计算结果再判断变的不可行(LeetCode不支持BigInteger)

开始解答:


import org.junit.Test;


public class trailingZeroe{

    @Test
    public void test() {
        int countZero = trailingZeroes(20);
        System.out.println("countZero = " + countZero);
    }


    /**
     * 求整数n阶乘后尾数中0的个数
     * @param n 整数
     * @return 阶乘后 尾数中 0 的数量
     */
    int trailingZeroes(int n) {
       int count = 0;
        for (int i = n; i > 0; i--) {
            count += trailingZeroesGetCount(i);
        }
        return count;
    }
    
    int trailingZeroesGetCount(int n) {
        int count = 0;
        if (n % 5 == 0) {
            count++;
            if ((n / 5) % 5 == 0) {
                count += trailingZeroesGetCount(n / 5);
            }
        }
        return count;
    }
    


}

提交结果(仅仅是通过了)

500 / 500 个通过测试用例

状态:通过

执行用时: 7 ms

内存消耗: 35.2 MB