Well, to compute the number of trailing zeros, we need to first think clear on what would generate a trailing 0 ? Obviously, a number multiplied by would has 10 a trailing 0 added to it. So we are need to find out how many's would appear in the expression of the 10 factorial. Since 10 = 2 * 5 and there is a bunch more 2 ' s (each even number would contribute at least one 2 ), we only need to count The number of 5 ' s.
Now let's see what numbers'll contribute a 5 . Well, simply the multiples of 5 , like 5, ten,, ... . So is the result simply n/5 ? Well, not. Notice that some numbers could contribute more than one 5 , like 5 * 5 . Well, what numbers would contribute more than one 5 ? Ok, notice that is only multiples of the power of 5 will contribute more than one 5 . For example, multiples of will contribute at least two 5 '.
Well, what to count them all? If You try some examples, you may finally get the result, which is n / 5 + n / 25 + n / 125 + ... . The idea behind this expression Is:all 5 the multiples of'll contribute one 5 , the multiples of'll 25 cont Ribute one more and the multiples of'll contribute another one more ... and so on 5 125 5 . Now, we can write down the following code, which are pretty short.
1 classSolution {2 Public:3 intTrailingzeroes (intN) {4 intCount =0;5 for(Long Longi =5; n/i; I *=5)6Count + = n/i;7 returncount;8 }9};
[Leetcode] Factorial Trailing Zeros