LeetCode172——阶乘后的零

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86488232

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/factorial-trailing-zeroes/description/

题目描述:

知识点:数学

思路:只有2和5相乘末尾才可能产生0

还有一个事实是,[1, n]范围内2的数量远远大于5的数量,因此有多少个5,乘积末尾就有多少个0。

对于2147483647的阶乘,我们可得下式:

2147483647!
=2 * 3 * ...* 5 ... *10 ... 15* ... * 25 ... * 50 ... * 125 ... * 250...
=2 * 3 * ...* 5 ... * (5^1*2)...(5^1*3)...*(5^2*1)...*(5^2*2)...*(5^3*1)...*(5^3*2)...

我们需要做的就是计算上式中有多少个5。

5中包含1个5,25中包含2个5,125中包含3个5……

因此我们的结果就是:

n/5 + n/25 + n/125 + n/625 + n/3125+...

注意,虽然25中包含了2个5,但其中一个5已经在n / 5中被计算过,后续同理。

JAVA代码:

public class Solution {
    public int trailingZeroes(int n) {
        int result = 0;
        long divider = 5;
        while(n / divider > 0){
            result += n / divider;
            divider *= 5;
        }
        return result;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86488232
今日推荐