问题描述
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路分析
给一个数,计算n!的后面有多少个零。
0来自10 = 2*5,组成n!的这些数中,2肯定比5要多的,所以这些数里有多少个5就会有多少个0,找出所有5的幂就可以了。
举个例子:n = 40;
那么所有带5的数有40、35、30、25、20、15、10、5,其中,25有两个5。所以我们用n除5,第一次找到的是51,然后是52。
总之,这是一个找5的游戏。
class Solution {
public:
int trailingZeroes(int n) {
int result = 0;
while(n != 0){
n = n/5;
result += n;
}
return result;
}
};
时间复杂度: O(logn)
反思
之前的错误做法中,有的变量没有初始化,导致最后瞎几把出结果,以后要注意变量的初始化。