[LintCode]Trailing Zeroes末尾ゼロの個数
2641 ワード
Write an algorithm which computes the number of trailing zeros in n factorial.
Have you met this question in a real interview?
Yes
Example
11! = 39916800, so the out should be 2
Challenge
O(log N) time
LeetCodeの原題は、私の前のブログFactorial Trailing Zeroesを参照してください.
解法1:
class Solution {
public:
// param n : description of n
// return: description of return
long long trailingZeros(long long n) {
long long res = 0;
while (n > 0) {
res += n / 5;
n /= 5;
}
return res;
}
};
解法2:
class Solution {
public:
// param n : description of n
// return: description of return
long long trailingZeros(long long n) {
return n == 0 ? 0 : n / 5 + trailingZeros(n / 5);
}
};