Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
先考虑0是怎么形成的?显然0是由2 * 5形成的。
所以,统计阶乘中的2因子和5因子即可得出0的个数。
因为5因子的个数一定是小于2因子的个数的,所以只需要统计5因子的个数。
如果是20的阶乘 ,5, 10, 15, 20 那么5因子会出现4次,所以会有4个0。
如果是25的阶乘,5,10,15,20,25。那么5因子会出现6次!因为25有2个5因子。
同样的125值会有3个5因子!!
做法是 n / 5 统计只有一个5因子的数的个数
n / 25,统计2个5因子的数的个数。
n / 125,统计3个5因子的数的个数。
...
代码:
public class FactorialTrailingZeroes {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
count += n / 5;
n /= 5;
}
return count;
}
}