题目描述:Given an integer n, return the number of trailing zeroes in n!.
Note : Your solution should be in logarithmic time complexity.
首先想到用组合数学的方法来算,n!中0的个数主要看的是1-n 各数的因数中2和5的次数,有多少对(2, 5),结果中就有多少个0,而分解的结果中,2的个数显然是多于5的,因此,有多少个5,就有多少个(2, 5)对。于是有了如下代码:
int trailingZeroes(int n) {
int weight = 5,sum = 0;
while(weight<=n){
sum += n/weight;
weight *= 5;
}
return sum;
}
但是,当测试数据n=2147483647时会TLE;改进后如下:
int trailingZeroes(int n) {
int sum = 0;
while(n>0){
sum += n/5;
n/=5;
}
return sum;
}