LeetCode 172. 阶乘后的零

目录结构

1.题目

2.题解

2.1直接计算

2.2计算因子5

2.3快速计算因子5


1.题目

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

示例:

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

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

说明: 你算法的时间复杂度应为 O(log n) 。 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/factorial-trailing-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

2.1直接计算

先算阶乘,然后通过取余判定末尾是否为零。

注意使用BigInteger防止溢出。

public class Solution172 {
    public int trailingZeroes(int n) {
        BigInteger tmp = BigInteger.ONE;
        for (int i = 2; i <= n; i++) {
            tmp = tmp.multiply(BigInteger.valueOf(i));
        }
        int result = 0;
        while (tmp.mod(BigInteger.TEN).equals(BigInteger.ZERO)) {
            tmp = tmp.divide(BigInteger.TEN);
            result++;
        }
        return result;
    }
}

2.2计算因子5

分析可得,

  • 尾部0的来自5×偶数,又偶数总比5多,故求有多少个因子5即可

对于参与阶乘的每个数通过取余判定。

public class Solution172 {
    public int trailingZeroes(int n) {
        int result = 0;
        for (int i = 5; i <= n; i += 5) {
            int t = i;
            while (t % 5 == 0) {
                result++;
                t /= 5;
            }
        }
        return result;
    }
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

2.3快速计算因子5

分析可得,

  • 尾部0的来自5×偶数,又偶数总比5多,故求有多少个因子5即可。
  •  同时25 有2个因子5,125有3个因子5...

故2.2计算因子5的个数实际上和\frac{n}{5}+\frac{n}{25}+\frac{n}{125}+...相等。

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

}
  • 时间复杂度:O(logn)
  • 空间复杂度:O(1)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值