目录结构
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;
}
}
- 时间复杂度:
- 空间复杂度:
2.3快速计算因子5
分析可得,
- 尾部0的来自5×偶数,又偶数总比5多,故求有多少个因子5即可。
- 同时25 有2个因子5,125有3个因子5...
故2.2计算因子5的个数实际上和相等。
public class Solution172 {
public int trailingZeroes(int n) {
int result = 0;
while (n > 0) {
n /= 5;
result++;
}
return result;
}
}
- 时间复杂度:
- 空间复杂度: