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.

1
2
3
4
5
6
7
8
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。

1
2
3
4
5
6
7
8
9
10
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;
}
posted @   bonelee  阅读(232)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示