Factorial Trailing Zeroes

来源:互联网 发布:如何评价黄海冰 知乎 编辑:程序博客网 时间:2024/06/06 18:40

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

Note: Your solution should be in logarithmic time complexity.



思路:如果要知道多少个0,就需要找到他们的约数中,有多少个2和5,由于2的个数必多于5,所以,找到5的个数即可

思路1:最笨的方法,暴力O(n),从2遍历到n,找到每个数中5的个数,累计求和

思路2:参考网上思路,给定一个数n,从1至n,仅含有一个5的数的个数为n/5,含有2个5的个数为n/25,因此,每次除以5的个数累计求和即可

代码:
class Solution {
public:
    int trailingZeroes(int n) {
        int res = 0;
        while(n){
            res += n/5;
            n /= 5;
        }
        return res;
    }
};
0 0
原创粉丝点击