class Solution {
public int trailingZeroes(int n) {
int ans = 0;//统计5的个数
for (int i = 5; i <= n; i += 5) {//只有5,10,15,20,25....会出现5,其它数字不会出现5
for (int x = i; x % 5 == 0; x /= 5) {//统计这些因子中的5的个数。例如100这个因子,可以拆解为5*5*4.有两个5
++ans;//5的个数
}
}
return ans;
}
}
数学优化:思路转变为求5的倍数的个数
解题思路:时间复杂度O( l o g 2 n log_2n log2n),空间复杂度O( 1 1 1)
class Solution {
public int trailingZeroes(int n) {
int count = 0;//统计个数
while (n != 0){//只要n的阶乘中还可以有5就继续
n /= 5;//获取n这个阶乘中所有5的倍数的个数
count += n;//统计个数
}
return count;
}
}