[leetcode] 172. Factorial Trailing Zeroes

本文介绍了一种简单而有效的算法,用于计算给定整数n的阶乘中末尾零的数量。通过分析可知,只需统计5的因子数量即可,因为2的因子数量总是远超5的因子数量。提供了C++和Python两种语言的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

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.

分析

题目的意思是:给定一个数n,求n!中0的个数。

  • 这道题目我感觉只要想明白了就很简单,2的个数远大于5的个数,所以只要统计5的个数就行了。

代码

class Solution {
public:
    int trailingZeroes(int n) {
        int res=0;
        while(n){
            res+=n/5;
            n=n/5;
        }
        return res;
    }
};

Python

下面用python实现一个不是那么高效,但是容易理解的算法:

class Solution:
    def trailingZeroes(self, n: int) -> int:
        res = 0
        for i in range(5,n+1,5):
            while i%5==0:
                i = i//5
                res+=1
        return res

参考文献

[LeetCode] Factorial Trailing Zeroes 求阶乘末尾零的个数

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值