Topic
Given an integer n, return the number of trailing zeroes in N!.
Note:your solution should is in logarithmic time complexity.
Analysis
Note that the time complexity of the logarithm is solved, then it is impossible to roughly calculate the factorial of N and then look at the number of 0 at the end.
So careful analysis, N! = 1 * 2 * 3 * ... * N and the number of the end 0 is only related to the number of the multipliers in 5 and 2, because each occurrence of a pair of 5 and 2 will produce a 10 then N! There must be a 0 at the end. However, further analysis will find that 2 of the number of factors is definitely greater than the number of 5, so we just need to find n! The total number of factor 5 can be.
1. Given n then N/5 will get all the 5*1, 5*2, 5*3 ... the number of
2.N/25 will get the number of all 25*1, 25*2, 25*3 ....
3.N/125 will get all 125*1, 125*2, 125*3 .... Number of
........
There may be doubt that 25 of the two 5,125 in 3 5 will be less, but careful observation will find that in the 1th step has been the case of 25, the 2nd step is equivalent to the other 5 statistics in, and so on
Code
1 Public int trailingzeroes (int n) {2 int rs = 0; 3 while (n! = 0) {4 rs + = (n/5); 5 n/= 5; 6 }7 return rs; 8 }
And that's the result.
Java computes the number of n factorial end 0-leetcode 172 factorial Trailing Zeroes