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

[leetcode] Factorial Trailing Zeroes

时间:2014-12-30 23:26:41      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

题目:(Math)

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

Note: Your solution should be in logarithmic time complexity.

 

题解:


首先列几个例子找一找规律。

然后发现

5!有一个0,

10!有两个0,

15!有三个0,

20!有四个0,

25!有六个0,。

可以看出当n大于等于5的时候就能产生后缀的0,因为5*2=10.而2又肯定不会缺因为只要有偶数就有2.

所以我们只要统计n!包含5的数目就可以。

一开始我以为只要n/5 就可以。后来发现例如25,里面包含了俩个5,25=5*5.所以发现5的总数 等于n/5 后的数再除以5 直到其小于5.

public class Solution {
    public int trailingZeroes(int n) {
        if(n<4)
          return 0;
          
        int res=0;
        while(n>=5)
        {
            res+=n/5;
            n=n/5;
        }
        return res;
    }
}

 

[leetcode] Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/fengmangZoo/p/4194753.html

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