Leetcode 172. Factorial Trailing Zeroes
172. Factorial Trailing Zeroes
Given an integer n
, return the number of trailing zeroes in n!
(n factorial).
Note: Your solution should be in logarithmic time complexity.
Q: What is the range of the input n
?
A: The input n
is a non-negative integer which can be as large as up to (10^9).
Q: Do we need to actually compute the factorial of n
?
A: No, we only need to count the number of trailing zeroes in n!
.
Q: What constitutes a “trailing zero”?
A: Trailing zeros are the number of consecutive 0
digits at the end of the number.
A trailing zero is produced by a factor of 10 in the number. Since 10 is the product of 2 and 5, each pair of these factors in the factorial contributes to a trailing zero. In any factorial, there are more factors of 2 than factors of 5, so the number of trailing zeros is determined by the number of factors of 5.
n
.public class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n >= 5) {
n /= 5; // Integer division to count multiples of 5, 25, 125, etc.
count += n;
}
return count;
}
}
n
by 5 before it becomes less than 5.This solution efficiently counts the number of trailing zeros in n!
without having to compute the factorial itself, making it suitable for very large values of n
as required.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?