LeetCode 172: Factorial Trailing Zeroes
Problem Description
Explanation
To count the number of trailing zeroes in the factorial of a number, we need to count the number of factors of 5 in the factorial. This is because the number of 5s in the prime factorization of a number will determine the number of trailing zeroes in its factorial. We can iteratively divide the number by 5 and sum up the quotients to get the total number of trailing zeroes.
Algorithm
- Initialize a variable
count
to 0. - Iterate over the numbers from 5 to n in steps of 5.
- For each number, divide it by 5 and add the quotient to
count
. - Return
count
as the number of trailing zeroes in n!.
Time Complexity
The time complexity of this algorithm is O(log n) since we are dividing the number by 5 in each iteration.
Space Complexity
The space complexity of this algorithm is O(1) as we are using only a constant amount of extra space.
Solutions
class Solution {
public int trailingZeroes(int n) {
int count = 0;
for (int i = 5; i <= n; i += 5) {
int num = i;
while (num % 5 == 0) {
count++;
num /= 5;
}
}
return count;
}
}
Related LeetCode Problems
Loading editor...