Leetcode: Factorial Trailing Zeroes

本文介绍了如何在对数时间内计算n的阶乘结果中尾部0的数量,并提供了两种C++实现方法。一种是对所有数进行遍历并检查是否可以被5整除,另一种则直接对能被5整除的数进行计数。

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

题目:
Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

即要求计算n的阶乘结果中后面0的个数。

分析:
对n!做质因数分解有:n!=2x*3y*5z*…
显然0的个数等于min(x,z),并且min(x,z)==z。
所以我们需要求n!中分解因式后5的个数。[n/k]代表1~n中能被k整除的个数,即我们需要求出n/5+(n-1)/5+(n-2)/5+…+1/5的个数。

下面使用C++语言进行示例:

所以,方法一:

class Solution {
public:
    int trailingZeroes(int n) 
    {
        int count = 0;
        int current;
        for (int i = 1; i <= n; i++)
        {
            current = i;
            while(current % 5 == 0)
            {
                count++;
                current /= 5;
            }
        }
        return count;
    }
};

但是,上面的示例中起作用的只有被5整除的那些数。能不能只对这些数进行计数呢?所以有方法二:

class Solution {
public:
    int trailingZeroes(int n) 
    {
        int count = 0;
        while(n)
        {
            count += n/5;
            n /= 5;
        }
        return count;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值