问题:
Given an integer n, return the number of trailing zeroes in n!.Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
代码:
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
class Solution {
public:
int trailingZeroes(int n) {
int retCnt=0,tmp5=5;
while(tmp5<=n){
// cout<<tmp5<<" "<<n<<endl;
retCnt+=n/tmp5;
tmp5*=5;
if(tmp5%5!=0) break;
}
return retCnt;
}
};
解析:
问题是给定整数n,返回n!中的尾随零数。
能够构成末尾0,其实决定因素在于1 to n 的数一共有多少个5因子。那么我们这样考虑:
对于5
那么能够被他整除的是 5 10 15 25 30 ...
这样其实便一共有n/5,对于 25 50 这样的数包括了两个5因子,我们在后面会计算的,在考虑5的时候,结果便是 n/5。
对于25
能够被整除的是 25 50 75 ...
这样,其实一共有n/25个,这时候25 中的两个5因子,变都计数了。
对于 125
同样能够被其整除的是125 625...
这样,是不是结果其实便是:
n/5 + n/25 + n/125 ...