Factorial Trailing Zeroes Leetcode

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!

 

posted @ 2017-01-22 05:09  璨璨要好好学习  阅读(118)  评论(0编辑  收藏  举报