国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > Leetcode 172 Factorial Trailing Zeroes

Leetcode 172 Factorial Trailing Zeroes

来源:程序员人生   发布时间:2017-02-07 09:06:43 阅读次数:2752次

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

Note: Your solution should be in logarithmic time complexity.

求阶乘的后缀0个数

乘法中的零来源于10,10来源于2和5,在阶乘中,1个数的质因子出现1次5,那末必定有其他数的质因子出现若干次2

所以问题变成求解质因子5出现的次数,

n/5求出包括1个5的数字个数

n/25求出包括两个5的数字个数...以此类推

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


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生