# 如何解leetcode Factorial Trailing Zeroes

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/24349.html | 发布：2023-10-12 | 更新：2023-10-12 | 分类：建站教程、投稿分享

**问题描述：**

  

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，只能是5乘以双数、或者某个乘数结尾为0，如10，但10可视为5*2，20可以视为5*4.

 

综上要想找n!中有几个0，其实就是寻求在1到n这n个数中有几个5.

 

其中25=5*5,这需要视为2个5

 

代码目的就变成了寻找1到n这n个数中5的个数

 

**代码：**

  

```
 def trailingZeroes(self, n: int) -> int:
          if n <= 0: return 0
        
          return sum( (n//(5**j)) for j in range(1, int(math.log(n, 5)) + 1))
```

  

n//(5**j) ，当j=1时，就是寻找在1到n这n个数中有几个5

 

n//(5**j) ，当j=2时，就是寻找在1到n这n个数中有几个25（5*5）（在上一步计算中，25会被统计,一次，但由于25是5*5，内部含有两个5，因而在第二步需要再统计一次，即一共是算为2次）

 

依次类推

 

最后将结果累计相加，就可以计算出就是寻找在1到n这n个数中有几个5了

 

```
 
```

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
