leetcode解题: Factorial Trailing Zeroes (172)

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

解法1: O(N), N is number of 5

一道老题了, 主要就是有一个5就会对应一个trailing zero, 题目要求的就变成从1到n有多少个数含有5的因子。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int trailingZeroes(int n) {
if (n < 5) {
return 0;
}
int count = 0;
while (n > 0) {
count += n / 5;
n = n / 5;
}
return count;
}
};

Java

1