Python3解leetcode Factorial Trailing Zeroes

问题描述:

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了

math.log(n, 5) 是求出以5为底,n的对数,然后向下取整,这个数就是j的最大值,因为如果j如果继续加1,那么5**j就会大于n,n//(5**j)恒为0,就没有计算意义了

猜你喜欢

转载自www.cnblogs.com/xiaohua92/p/11109787.html