Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
---
Solution: The idea is to count the number of factors of 5 in all of the numbers from 1 to n inclusive. 5, 10, 15, 20 count as one factor of 5 each. 25 counts as two factors of 5. We count the number of 5's because a zero is obtained by multiplying 2 by 5, and since there are surely more factors of 2 than factors of 5, we only need to count the number of 5'.
A good lengthy explanation beyond what I can write:
http://www.programmerinterview.com/index.php/java-questions/find-trailing-zeros-in-factorial/
public class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n >= 5) {
n /= 5;
count += n;
}
return count;
}
}
No comments:
Post a Comment