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

    class Solution(object):
        def trailingZeroes(self, n):
            # 15!=3, 15/5=3
            # 25!=6, 25/5=5+5^2|1
            # count 5 number
            if n < 5:
                return 0
            return n/5 + self.trailingZeroes(n/5)
    

     思考这类问题还是要从上而下思考,先用递归思路去解,最后修改循环或者dp。

    class Solution(object):
        def trailingZeroes(self, n):
            # 15!=3, 15/5=3
            # 25!=6, 25/5=5+5^2|1
            # count 5 number
            ans = 0
            while n >= 5:
                ans += n/5
                n = n/5
            return ans                
    

     另外的解法:

    Example Three

    By given number 4617.

    5^1 : 4617 ÷ 5 = 923.4, so we get 923 factors of 5

    5^2 : 4617 ÷ 25 = 184.68, so we get 184 additional factors of 5

    5^3 : 4617 ÷ 125 = 36.936, so we get 36 additional factors of 5

    5^4 : 4617 ÷ 625 = 7.3872, so we get 7 additional factors of 5

    5^5 : 4617 ÷ 3125 = 1.47744, so we get 1 more factor of 5

    5^6 : 4617 ÷ 15625 = 0.295488, which is less than 1, so stop here.

    Then 4617! has 923 + 184 + 36 + 7 + 1 = 1151 trailing zeroes.

    C/C++ code

    int trailingZeroes(int n) {
        int result = 0;
        for(long long i=5; n/i>0; i*=5){
            result += (n/i);
        }
        return result;
    }
    
  • 相关阅读:
    springboot集成kafka
    elasticsearch http 搜索 测试
    linux下安装Elasticsearch
    laravel_admin 使用
    laravel 数据操作
    Win10+apache+PHP+Mysql
    laravel 坑(一)
    下载CentOS镜像
    window10 家庭版 添加Hyper-V虚拟机
    Win10 Composer 下载安装
  • 原文地址:https://www.cnblogs.com/bonelee/p/9349806.html
Copyright © 2011-2022 走看看