Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
一开始就想1~n中统计被2整除和被5整除的因子有多少,取两个中较小的。但复杂度是O(nlgn),不符合题目要求。
class Solution {
public:
int trailingZeroes(int n) {
int cnt1=0,cnt2=0;
for(int j=1;j<=n;j++){
int i=j;
while(i%5==0){
cnt1++;
i/=5;
}
/*
while(i%2==0){
cnt2++;
i/=2;
}
*/
}
return min(cnt1,cnt2);
}
};
后来看了结题报告 题解
(有详细的证明)
原来只要看被5整除就行了,而且[n/k]就是1~n中被k整除的数的多少。所以只要看n被5,25,125…整除的数量就好了,复杂度是O(lgn)。这题只有下一种方法能过。
class Solution {
public:
int trailingZeroes(int n) {
int cnt1=0,cnt2=0;
while(n){
cnt1 += n/5;
n/=5;
}
return cnt1;
}
};