172. Factorial Trailing Zeroes
Posted thinker-pcw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了172. 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.
来自 <https://leetcode.com/problems/factorial-trailing-zeroes/description/>
思路1:耿直的想法,把阶乘算出来,然后计算末尾有多少个0
1 class Solution(object): 2 def trailingZeroes(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 num = 1 8 for i in range(1, n + 1): 9 num = num * i 10 num = str(num)[::-1] 11 count = 0 12 for i in num: 13 if i == ‘0‘: 14 count += 1 15 else: 16 break 17 return count
思路2:问题的关键在于2和5的出现次数,因为只有2*5才能组成10,但2的出现概率是高于5的,所以只要计算5的出现次数就行了,如5!包含1个5,10!包含5和10这两个,25!包含5,10,15,10,25,其中25又可以分成5*5也就是6个。所以问题可以转换为求解包含5,5*5,5*5*5…的个数
1 class Solution(object): 2 def trailingZeroes(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 count = 0 8 while (n > 0): 9 count += n // 5 10 n = n / 5 11 return int(count)
以上是关于172. Factorial Trailing Zeroes的主要内容,如果未能解决你的问题,请参考以下文章
172. Factorial Trailing Zeroes
172. Factorial Trailing Zeroes
172. Factorial Trailing Zeroes
172. Factorial Trailing Zeroes