Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
要求对数时间。
首先分析,只有2*5=10才会产生一个0,N!中2的数量永远大于5的数量,所以该题的目标简化为求N!中5的个数。
第一种方法是求1~N中每个数中含有5的个数,加起来便是结尾0的个数,但时间复杂度非log级;
第二种,寻求一种思路,N!中5的个数=[N/5]+[N/25]+[N/125]+...,下面是代码,感受一下
int trailingZeroes(int n) {
int count = 0;
while(n)
{
count += n/5;
n /= 5;
}
return count;
}