题目
Write a program that will calculate the number of trailing zeros in a factorial of a given number. N! = 1 2 3 … N Be careful 1000! has 2568 digits… 写一个程序来计算一个给定数的阶乘中的尾随零的个数。 N!= 1 2 3 … N 注意 1000!有2568个数字。。。
例子
zeros(6) = 1
6! = 1 2 3 4 5 * 6 = 720 —> 1 trailing zero
zeros(12) = 2
12! = 479001600 —> 2 trailing zeros
分析
直接求这个数的阶乘再判断有几个0并不合适,应该用其他的方式去判断最后的结果有几个0。我们注意到判断结尾有几个0其实就等价于判断这个数是5、55 、55*5 …的几倍,将他们加起来就是结尾0的个数了。
我的解法
public class Solution {
public static int zeros(int n) {
int zeros = 0;
int i = 5;
while (n/i > 0){
zeros += n/i;
i = i*5;
}
return zeros;
}
}
参考解法
public class Solution {
public static int zeros(int n) {
int res = 0;
for (int i = 5; i <= n; i *= 5) {
res += n / i;
}
return res;
}
}
public class Solution {
public static int zeros(int n) {
if(n/5 == 0)
return 0;
return n/5 + zeros(n/5);
}
}
提升
- 抓住问题的关键点,求0的个数,所以并不需要求阶乘
- 容易忽视 5 —>1个0、 25 —>2个0
- 用递归写法更优雅,更容易理解,但时间和空间的消耗比较大,自行取舍吧