LeetCode--Factorial Trailing Zeroes(注意)

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;
    }
原文地址:https://www.cnblogs.com/little-YTMM/p/4513224.html