172. Factorial Trailing Zeroes
Problem
Return how many trailing zeros n! has.
Example: 3 → 0; 5 → 1 (5! = 120)
Constraints: n ≤ 10⁴. Follow-up: logarithmic time.
Each trailing zero needs a factor 10 = 2 · 5, and 2s are plentiful, so count factors of 5: n/5 + n/25 + n/125 + ….
Complexity: O(log n).
class Solution:
def trailingZeroes(self, n: int) -> int:
count = 0
while n:
n //= 5
count += n
return count
assert Solution().trailingZeroes(3) == 0
assert Solution().trailingZeroes(5) == 1
assert Solution().trailingZeroes(100) == 24
class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) { n /= 5; count += n; }
return count;
}
}
func trailingZeroes(n int) int {
count := 0
for n > 0 { // count the factors of 5 (there are always more 2s)
n /= 5
count += n
}
return count
}