题目描述
思路
求结果中尾随零的数量,本质上是求出一共有多少个10相乘,即:n*(n-1*(n-2)*...*3*2*1
可以等价于(m1*m2*...)*10*10*...*10
而 10 = (2*5)
,所以本质上是求数列中2或5的个数(取最小值,也就是求5的个数)
代码
class Solution {
public int trailingZeroes(int n) {
int count =0;
for(int i=5 ; i<=n; i+=5){
for(int j =i; j%5 == 0; j/=5){
count++;
}
}
return count;
}
}
进阶版
class Solution {
public int trailingZeroes(int n) {
int ans = 0;
while (n != 0) {
n /= 5;
ans += n;
}
return ans;
}
}