2020年5月5日
LeetCode 172. Factorial Trailing Zeroes
C++, LeetCode, 算法, 编程
0 Comments
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero.
Note: Your solution should be in logarithmic time complexity.
解析:求解n的阶乘结果中末尾0的个数。0的结果来源于10,10=2*5,并且2的个数远大于5,因此只需要求解5的个数就可以了。所以可以写成n/5。但是像25这种,包含5的数量却是6.类似的有5*5, 5*5*5, 5*5*5*5。代码如下:
class Solution {
public:
int trailingZeroes(int n) {
int res = 0;
while(n)
{
res += n/5;
n /= 5;
}
return res;
}
};
参考: