给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5 输出: 1 解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
最开始我是这样写的,但是n大了的时候,会抛出StackOverFlowError(线程请求的栈深度大于虚拟机允许的深度。)
class Solution {
public int trailingZeroes(int n) {
int result=jiecheng(n);
int count=0;
while(result!=0){//求几个0
if(result%10==0) count++;
result/=10;
}
return count;
}
private int jiecheng(int n){//求阶乘结果
if(n==0) return 1;
if(n==1||n==2) return n;
int multiply=n*jiecheng(n-1);
return multiply;
}
}
所以查了一下大家都是怎么实现的
1×5 → 5! → 1个0
2×5 → 10! → 2个0
3×5 → 15! → 3个0
4×5 → 20! → 4个0
5×5 → 25! → 6个0
6×5 → 30! → 7个0
7×5 → 35! → 8个0
8×5 → 40! → 9个0
9×5 → 45! → 10个0
10×5 → 50! → 12个0
11×5 → 55! → 13个0
---------------------
作者:努力努力再努力Sunny
原文:https://blog.csdn.net/z983002710/article/details/81100762
class Solution {
public int trailingZeroes(int n) {
int count=0;
while(n!=0){
n/=5;
count+=n;
}
return count;
}
}