题目描述:
Write an algorithm which computes the number of trailing zeros in n factorial.
Example
题目思路:
11! = 39916800, so the out should be 2
这题就是算数字中有多少个5:一个5代表1个0,一个25代表2个0,...
将n不断整除5,第一次整除表示算出n中有多少个5,第二次整除表示算n中有多少个25 (相当于n/5中有多少个5),...
这样把每次整除得到的答案加起来就可以了。
Mycode(AC = 5ms):
class Solution {
public:
// param n : description of n
// return: description of return
long long trailingZeros(long long n) {
long long ans = 0, tmp = n;
while (tmp >= 1) {
ans += tmp / 5;
tmp /= 5;
}
return ans;
}
};