leetcode 172. Factorial Trailing Zeroes

此题是求阶乘结果数字尾部有几个零
1)先计算阶乘,再计算尾部几个零
缺点:时间复杂度高,阶乘结果存在溢出的情况

class Solution {
public:
    long long factorial(int n)
    {
        long long result=1;
        while(n>0)
        {
            result*=n;
            n--;
        }
        return result;
    }
    int trailingZeroes(int n) {
        long long temp=factorial(n);
        int count=0;
        while(temp!=0)
        {
            int left=temp%10;
            if(left==0)
                count++;
            else
                break;
            temp/=10;
        }
        return count;
    }
};

2)若将整个阶乘进行因式分解,其结果尾部的0只能由5*2构成,而其中2的数目远远大于5的数目,尾部0的数目由阶乘中5的因子数目决定。
按照阶乘公司,每一个数进行对5的因式分解,将其中含有5的数目进行相加。
缺点:时间复杂度高

10!=5x2x9x2x2x2x7x3x2x5x2x2x3x2x1=3628800

class Solution {
public:
    int factor(int n)
    {
        int result=0;
        while(n!=0&&n%5==0)
        {
            result++;
            n/=5;
        }
        return result;
    }
    int trailingZeroes(int n) {
        int count=0;
        int index=0;
        while(index<=n)
        {
            int num=factor(index);
            count+=num;
            index+=5;
        }
        return count;
    }
};

3)利用公式
num=N/5+N/(5^2)+…直到末项为0
举例如下:
30阶乘中含有5的数为30 25 20 15 10 5
30/5=6 表示有6个数含有5的因子
30/25=1 表示有1个数含有两个5的因子,上例中即为25
30/125=0 表示没有任何一个数含有3个5的因子

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值