leetcode + n!后面有多少尾部0, 看2和5的个数

点击打开链接
class Solution {
public:
    int trailingZeroes(int n) {
        //计算包含的2和5组成的pair的个数就可以了
        //因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。
        //观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。
        //但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),
        //所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商为0。
        int result = 0,k=0;
        while(n > 0){
            k = n/5;
            result += k;
            n = k;
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/80923579
今日推荐