[LeetCode 172] Factorial Trailing Zeros
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
To determine how many trailing zeroes there will be for n!, we need to find out how many 10s that all the numbers from 1 to n can contribute. 10 = 2 * 5, since we'll have more 2s than 5s, we just need to count up how many factor 5 we'll have from 1 to n.
We achieve the above goal by counting 5 in layers. K = n / 5, we have K 5s. (5 * 1, 5 * 2, ........, 5 * K). Because there are numbers like 25, 50, 75 that offers more than one 5, we need to keep counting. How do we do this? After dividing 5 in the first round of counting, we should update the new n to be n / 5 and repeat the above process. Doing this represent that we've already counted all 5s from the previous round, now we need to ignore these, and count more 5s if any number can contribute more 5s.
Take n = 50 as an example,
K = 50 / 5 = 10, we have 10 5s from 5, 10, 15, 20, 25, 30, 35, 40, 45, 50; update n to K, n = 10;
K = 10 / 5 = 2, we have another 2 5s from 25 and 50; if we take a look at 1,2,3,4,5,6,7,8,9,10, which is the result of dividing 5 from the above list, we know that only 5 and 10 can contribute another 5. update n to 2;
Now the list is 1 and 2, representing 25, 50 divided by 5^2. K = 2 / 5 = 0, n = 0, terminate as we do not have more 5s to count.
The key here is that at each step, we filter potential 5 contributing candidates. If a number stops contributing 5 at a particular round, it is not going to make more contributions in future rounds. So the candidate list is shrinking by a factor of 5.
class Solution { public int trailingZeroes(int n) { int fiveCnt = 0; while(n > 0) { int k = n / 5; fiveCnt += k; n = k; } return fiveCnt; } }