Description
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.
分析
题目的意思是:给定一个数n,求n!中0的个数。
- 这道题目我感觉只要想明白了就很简单,2的个数远大于5的个数,所以只要统计5的个数就行了。
代码
class Solution {
public:
int trailingZeroes(int n) {
int res=0;
while(n){
res+=n/5;
n=n/5;
}
return res;
}
};
Python
下面用python实现一个不是那么高效,但是容易理解的算法:
class Solution:
def trailingZeroes(self, n: int) -> int:
res = 0
for i in range(5,n+1,5):
while i%5==0:
i = i//5
res+=1
return res