Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
这个题目参考了Simple C/C++ Solution (with detailed explaination)和My one-line solutions in 3 languages这两个discuss。
思路就是:0是从10来的,10是从2x5来的,2总是充足的,所以只需要计算5的个数就行了,但是要注意5x5=25、5x5x5=125···
详细解释可参见第一个discuss,讲的挺详细的。
C++代码如下:
int trailingZeroes(int n) {
int result = 0;
for(long long i = 5; n / i > 0; i *= 5) {
result += (n / i);
}
return result;
}
第二个讨论原理与上同,但是用递归的方法只用一行代码就解决了这个问题,在此也MARK一下:
int trailingZeroes(int n) {
return n < 5 ? 0 : n / 5 + trailingZeroes(n /5);
}