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

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

题目描述:

LeetCode172——阶乘后的零

知识点:数学

思路:只有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解题报告:

LeetCode172——阶乘后的零

 

相关文章:

  • 2022-12-23
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2021-05-16
  • 2021-08-18
  • 2022-12-23
  • 2021-12-26
猜你喜欢
  • 2022-12-23
  • 2022-01-14
  • 2021-09-23
  • 2021-11-09
  • 2021-04-24
  • 2022-02-08
  • 2022-01-03
相关资源
相似解决方案