首页 > 其他 > 详细

[leetcode] Factorial Trailing Zeroes

时间:2014-12-30 23:26:18      阅读:480      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!