Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
I, in general, don't like the math programming questions... they are pretty tricky but would be very easy once you rule it.
This one actually is an exceptional....
int trailingZeroes(int n) {
int count = 0;
for(long long int i = 5; i <= n; i = i * 5) {
count += n / i;
}
return count;
}
Do it recursively.... so neat!
public int trailingZeroes(int n) {
return n>=5 ? n/5 + trailingZeroes(n/5): 0;
}

本文介绍了一种使用递归方法计算阶乘尾部零数的算法,通过逐步除以5来计数零的个数,以达到在对数时间内解决问题的目的。

被折叠的 条评论
为什么被折叠?



