首页 > 其他 > 详细

Factorial Trailing Zeroes Leetcode

时间:2017-01-22 08:10:03      阅读:258      评论:0      收藏:0      [点我收藏+]

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

Note: Your solution should be in logarithmic time complexity.

这道题首先要读懂题目。。。一开始连factorial是阶乘的意思都不懂。。。

public class Solution {
    public int trailingZeroes(int n) {
        int sum = 0;
        while (n >= 1) {
            sum += n / 5;
            n /= 5;
        }
        return sum;
    }
}

阶乘之后有多少个0主要看这个数里面有多少个5,因为2*5 =10然而2的数量总是比5多。

public class Solution {
    public int trailingZeroes(int n) {
        int sum = 0;
        long x = 5;
        while (x <= n) {
            sum += n / x;
            x *= 5;
        }
        return sum;
    }
}

这个方法是每次除以5,然后除以25,因为25里面有两个5要加上多余的次数。但要注意一定要用long!

 

Factorial Trailing Zeroes Leetcode

原文:http://www.cnblogs.com/aprilyang/p/6339324.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!