ITeye博客

Factorial Trailing Zeroes

KickCode · 2016-02-17 01:43 · Leetcode · 编程语言 · Markdown

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;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。