Leetcode-172 [Difficulty: Medium]
Given an integer n, return the number of trailing zeroes in n!.
Note that .
Example 1:
Example 2:
Example 3:
Constraints:
Follow up: Could you write a solution that works in logarithmic time complexity?
Problem Explanation:
Key Insight:
Algorithm:
Time/Space Complexity:
Solution-1: Logrithmic approach
Dividing the input by 5.
public int trailingZeroes(int n) {
int count = 0;
while( n > 0) {
n = n / 5;
count += n;
}
return count;
}
Increasing a divisor with power of 5.
public int trailingZeroes(int n) {
int count = 0;
int pof = 5;
while(n >= pof) {
count += n / pof;
pof *= 5;
}
return count;
}
Solution-1: Bruteforce approach
Approach:
Time Complexity:
Space Complexity:
Limitations:
Integer Overflow:
Inefficiency:
Note:
Implementation:
public class TrailingZerosInFactorialBruteForce {
// Function to compute the factorial of a number
public static long computeFactorial(int n) {
long factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
// Function to count trailing zeros in the factorial
public static int countTrailingZeros(int n) {
// Compute the factorial of n
long factorial = computeFactorial(n);
// Count the number of trailing zeros
int count = 0;
while (factorial > 0) {
if (factorial % 10 == 0) {
count++;
factorial /= 10;
} else {
break;
}
}
return count;
}
}