题目如下:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
分析如下:
看上去简单,但是写出logarithmic time complexity的代码还是需要一些思考的。分析在下面的代码注释中。
我的代码:
// 88ms
class Solution {
public:
int trailingZeroes(int n) {
//计算包含的2和5组成的pair的个数就可以了,一开始想错了,还算了包含的10的个数。
//因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。
//观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。
//但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),
//所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商为0。
int count_five = 0;
while ( n > 0) {
int k = n / 5;
count_five += k;
n = k;
}
return count_five;
}
};
/*
// TLE版本
class Solution {
public:
int trailingZeroes(int n) {
//计算包含的2和5组成的pair的个数就可以了,一开始想错了,还算了包含的10的个数。
//因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。
//观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n / 15就可以。
//但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25的另外一个5),
//所以除了计算n / 15, 还要计算n/15/15/../15直到商为0。
int count_five = 0;
for (int i = 1; i <=n; ++i) {
int current = i;
while (current%5 == 0) {
current /= 5;
count_five++;
}
}
return count_five;
}
};
*/
对 时间复杂度的名词解释备忘在这里。