- LeetCode(172) Factorial Trailing
- LeetCode 172 [Factorial Trailing
- leetcode:172. Factorial Trailing
- [String]172. Factorial Trailing
- LeetCode 172. Factorial Trailing
- Leetcode 172. Factorial Trailing
- LeetCode 172. Factorial Trailing
- Leetcode.172.Factorial Trailing
- Leetcode 172. Factorial Trailing
- 172. Factorial Trailing Zeroes
Factorial Trailing Zeroes
今天是一道LeetCode上easy的题目,Acceptance为29.8%。
题目如下:
Given an integer n, return the number of trailing zeroes in n!.
**Note: **Your solution should be in logarithmic time complexity.
Credits:Special thanks to @ts for adding this problem and creating all test cases.
该题虽然为easy的题目,但是第一次看到可能还真的想不出好的解题思路。
思路如下:
这里我们要求n!
末尾有多少个0
,因为我们知道0
是2
和5
相乘得到的,而在1
到n
这个范围内,2
的个数要远多于5
的个数,所以这里只需计算从1
到n
这个范围内有多少个5
就可以了。
思路已经清楚,下面就是一些具体细节,这个细节还是很重要的。
我在最开始的时候就想错了,直接返回了n / 5
,但是看到题目中有要求需要用O(logn)的时间复杂度,就能够想到应该没这么简单。举连个例子:
例1
n=15
。那么在15!
中 有3
个5
(来自其中的5
, 10
, 15
), 所以计算n/5
就可以。
例2
n=25
。与例1相同,计算n/5
,可以得到5
个5
,分别来自其中的5, 10, 15, 20, 25
,但是在25
中其实是包含2
个5
的,这一点需要注意。
所以除了计算n/5
, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5
直到商为0,然后就和,就是最后的结果。
代码如下:
java版
class Solution {
/*
* param n: As desciption
* return: An integer, denote the number of trailing zeros in n!
*/
public long trailingZeros(long n) {
// write your code here
return n / 5 == 0 ? 0 : n /5 + trailingZeros(n / 5);
}
};
C++版
class Solution {
public:
int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
};
网友评论