172. Factorial Trailing Zeroes

题目:

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

Note: Your solution should be in logarithmic time complexity.

链接: http://leetcode.com/problems/factorial-trailing-zeroes/

题解:

求n!里有多少个0。其实主要就是看有多少个5,有多少个5就有多少个0,这样我们就可以用一个while循环来搞定。

Time Complexity - O(logn), Space Complexity - O(1)

public class Solution {
    public int trailingZeroes(int n) {
        if(n <= 0)
            return 0;
        
        int res = 0;
        while(n > 0) {
            res += n / 5;
            n /= 5;
        }    
        
        return res;    
    }
}

 

二刷:

找到在n里有多少个5,就可以得到结果。

Java:

Time Complexity - O(logn), Space Complexity - O(1)

public class Solution {
    public int trailingZeroes(int n) {
        if (n < 5) {
            return 0;
        }
        int count = 0;
        while (n > 0) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
}

 

三刷:

题目可以转化为,求n!中含有多少个5。如何计算一个数里面有多少个5呢?我们可以用以下公式:

count = n / 5 + n / 25 + n / 125 + ....

就是用n除5来取得一开始的基数,当遇到5的倍数的时候,我们也要作相应的增加, 转换为循环的话我们可以先计算单个5的个数  n / 5,然后 n /= 5来计算 25的个数,然后再继续。最后返回count.

Java:

Time Complexity - O(logn), Space Complexity - O(1)

public class Solution {
    public int trailingZeroes(int n) {
        if (n < 5) {
            return 0;
        }
        int count = 0;
        while (n > 0) {
            count += n / 5;
            n /= 5;
        }
        return count;
    }
}

 

 

Reference:

https://leetcode.com/discuss/62976/my-python-solution-in-o-1-space-o-logn-time

https://leetcode.com/discuss/19847/simple-c-c-solution-with-detailed-explaination

http://15838341661-139-com.iteye.com/blog/1883889

posted @ 2015-05-10 03:47  YRB  阅读(348)  评论(0编辑  收藏  举报