leetcode :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的阶乘后面有几个0。从1数到n,最多只能被5整除的贡献一个,被25整除的贡献2两个。所以代码是这样

class Solution {
public:
int trailingZeroes(int n) {
        int c = 5;
        int counts = 0;
        while (c <= n) {
            counts += n / c;
            if(c != (c * 5)/5) {         //判断溢出
                break;
            }else {
                c *= 5;
            }
        }
        return counts;
    }
};

乘法的判断溢出不能用符号是否改变什么的判断,之前使c <= 0作为判断结果溢出了没找出来。

上面的情况避免溢出更好的办法是用除法替代乘法(因为被除数大于1,越除越向0靠拢,所以不会溢出)

class Solution {
public:
    int trailingZeroes(int n) {
        int counts = 0;
        while (n) {
            counts += n / 5;
            n /= 5;
        }
        return counts;
    }
};

 

posted on 2015-07-15 16:06  远近闻名的学渣  阅读(114)  评论(0)    收藏  举报

导航