题目:Given an integer n , return the number of trailing zeroes in n! .
Note: Your solution should be in logarithmic time complexity.
解析:计算阶层尾0数目的公式为 N = n / 5 + n / 5^2 + n / 5^3 + …
代码如下:
/ 时间复杂度 O(log n)
// res = n/5 + n/(5^2) + n/(5^3) + ...
class Solution {
public:
int trailingZeros(int n) {
int res = 0;
while (n > 0) {
res += n / 5;
n /= 5;
}
return res;
}
};