阶乘后的零

一、题目

172. 阶乘后的零

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

提示 n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1

示例 1:

输入:n = 3
输出:0
解释:3! = 6 ,不含尾随 0

示例 2:

输入:n = 5
输出:1
解释:5! = 120 ,有一个尾随 0

示例 3:

输入:n = 0
输出:0

提示:

  • 0 <= n <= 104

进阶:你可以设计并实现对数时间复杂度的算法来解决此问题吗?

二、题解

题解一(BigInteger方式)

好像Leetcode无法识别BigInteger,所以提交失败

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static int trailingZeroes(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
BigInteger bigInteger = BigInteger.valueOf(i);
result = result.multiply(bigInteger);
}
String string = result.toString();
int zeros = 0;
for (int i = string.length() - 1; i >= 0; i--) {
if (Objects.equals(string.charAt(i), '0')) {
zeros++;
}else {
return zeros;
}
}
return zeros;
}

题解二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static 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;
}

image-20241213171147773

三、总结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.loltoulan.other;

import java.math.BigInteger;
import java.util.Objects;

public class TrailingZeroes {

public static void main(String[] args) {
System.out.println(trailingZeroes(5));
}

public static int trailingZeroes1(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
BigInteger bigInteger = BigInteger.valueOf(i);
result = result.multiply(bigInteger);
}
String string = result.toString();
int zeros = 0;
for (int i = string.length() - 1; i >= 0; i--) {
if (Objects.equals(string.charAt(i), '0')) {
zeros++;
}else {
return zeros;
}
}
return zeros;
}

public static 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;
}
}