方法一:
O(n) 的时间复杂度
因为只有 2 * 5 = 10 会在结尾产生一个 0 ,因此我们就计算阶乘中每一个数能被 2 除尽的次数,即能被分解出多少个 2 ,同理我们可以求出阶乘中每一个数可以被分解出多少个 5 ,然后取 2 和 5 的最少个数,就是最后结果中含有 10 的倍数,也即结尾有多少个 0 。
class Solution {
public int trailingZeroes(int n) {
int fivecount = 0;
for(int i = 5; i <= n; i+=5) {
int current = i;
while (current % 5 == 0) {
fivecount++;
current /= 5;
}
}
return fivecount;
}
}
方法二:
O(logn)的时间复杂度
class Solution {
public int trailingZeroes(int n) {
int zeroCount = 0;
long currentMultiple = 5;
while (n > 0) {
n /= 5;
zeroCount += n;
}
return zeroCount;
}
}
不是很明白!!!