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

问题描述:给出一个正整数n,计算n!结构后面有几个0.要求:在多项式时间中完成算法。

常规思路:计算n!,然后统计一下后面有几个0,但是这种算法一想就知道肯定会超出时间限制。

巧妙思路:相乘得0,则只有2*5相乘能得到0;而0的个数也只会与2、5的个数有关,而一个数一定能分解成1^x1+2^x2+3^x3+5^x5+7^x7+……的形式,而且2的幂方数一定比5的幂方数多;

2*5=10;

2*5*2*5=100;

即有几个5一定会有几个2与之配套,有几套2-5,则便会有几个零。

代码如下:

public int trailingZeroes(int n) {
        int count = 0;
        for( ; n/5>=1;){
            count = count + n/5;
            n = n/5;
        }
        return count;
    }

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-23
  • 2021-06-07
  • 2021-09-05
  • 2021-08-22
  • 2021-06-03
  • 2022-02-23
猜你喜欢
  • 2021-12-18
  • 2022-02-20
  • 2021-09-01
  • 2021-05-20
  • 2021-11-02
相关资源
相似解决方案