原题:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路:
数字结尾每个0相当于一组2与5的乘积,因子只要知道n!中包含多少对质因子2和5,结尾就有多少个0. 由于质因子2的个数必然大于质因子5的个数,所以只要统计n!中质因子5的个数即可。
代码(Java):
public class Solution {
public int trailingZeroes(int n)
{
int res = 0;
while(n > 0)
{
res += n/5;
n = n/5; //对应25,125,625...这类情况
}
return res;
}
}