码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode--Factorial Trailing Zeroes(注意)

时间:2015-05-19 00:27:44      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

 

LeetCode--Factorial Trailing Zeroes(注意)

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4513224.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!