Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

给定一个整数n,让我们判断n的阶乘中末尾有几个零。我们只需要知道n的阶乘中有几个2和5的组合就可以,每个5前面都会有一个尾数为2的值,对于本身尾数为0的我们可以理解为它本身就是一个2和5的组合。这样我们只需要知道5的个数就可以了。代码如下:
public class Solution {
    public int trailingZeroes(int n) {
        int count = 0;
        while(n > 0) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2276827
今日推荐