码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 172. Factorial Trailing Zeroes

时间:2018-07-22 13:59:41      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:span   ber   for   function   pytho   while   tor   nat   class   

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;
}

leetcode 172. Factorial Trailing Zeroes

标签:span   ber   for   function   pytho   while   tor   nat   class   

原文地址:https://www.cnblogs.com/bonelee/p/9349806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!