Write an algorithm which computes the number of trailing zeros in n factorial.
Have you met this question in a real interview?
Yes
Example
11! = 39916800, so the out should be 2
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
我们会发现: the number of 2s in prime factors is always more than or equal
to the number of 5s. So if we count 5s in prime factors, we are done. How to count total number of 5s in prime factors of n!? A simple way is
to calculate floor(n/5). 问题转化为求阶乘过程中质因子5的个数,但是要注意25能提供2个5,125能提供3个5....
所以,count= floor(n/5) + floor(n/25) + floor(n/125) + ....
*/ public class Solution {
public int trailingZeroes(int n) {
if (n < ) return ; int r = ;
while (n > ) {
n /= ;
r += n;
}
return r;
}
}