zoukankan      html  css  js  c++  java
  • 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)

      

  • 相关阅读:
    python基本数据类型之整型和浮点型
    Java学习路线
    Linux学习笔记之VIM
    Java基础之流程控制
    Linux学习笔记之Shell
    Java基础之数据类型
    论文提交说明
    IDEA安装教程
    Link summary for writing papers
    1 类基础知识
  • 原文地址:https://www.cnblogs.com/Thinker-pcw/p/9513718.html
Copyright © 2011-2022 走看看