题目
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
解析
class Solution {//0来自于5*2,因为2的个数总是大于等于5,所以有多少个零就看有多少个5
public:
int trailingZeroes(int n) {
return n==0?0:n/5+trailingZeroes(n/5);
}
};
代码很简单。
问题 是求解n!结果后面有多少个零。
很容易看出0是来自于5*2,因为n!中,2的个数要多于5,所以要计算因子5有多少个。
5,10,15,20,25,...50,55等效为
1*5,2*5,3*5,...10*5,11*5
可以看到是(1,2,3,4,5,...11)*5
括号里等效为n/5的子问题,所以结果是n/5+trailingZeroes(n/5).