题目
思路
- 要找因子中出现了几对<2,5>,由于因子2的数量总是比因子5要多,所以找因子中5出现的次数就行了。所以,每次
x%5=0
,count++
- 但是有的数字存在一个以上的因子。例如,若
n = 25
,那么我们只做了count += 1
。但是我们应该count += 2
,因为25有两个因子 5。 - 所以使用
while
而不是if
语句,若有因子5就将数字除以5。如果还有剩余的因子5,则重复步骤。
代码
class Solution {
public int trailingZeroes(int n) {
int count = 0;
for (int i = 5; i <= n; i += 5) {
int cur = i;
while (cur % 5 == 0) {//25->5->1
count++;
cur /= 5;
}
}
return count;
}
}