阶乘末尾0的个数问题

问题:给定一个整数N,那么N的阶乘N!末尾有多少个0? 比如:N=10,N!=3628800,N!的末尾有2个0,写出算法。

回答:

int countZero(int N) {
    int ans = 0;
    int maxInt = 1000000000;//10^9
    int  tmpn = N;
    while(tmpn){
        maxInt /= 10;
        tmpn /= 10;
    }
    int lastBit = 1; //保存上一个阶乘 的最后 K位数字
    for (int i = 2; i <= N; i++) {
        int cnt = 0;//新增加的0的个数
        int tmp = lastBit * i;

        while ((tmp % 10) == 0) {
            tmp /= 10;
            cnt++;
        }
        //防止计算溢出
        if (tmp > maxInt)
            tmp = tmp % maxInt;
        lastBit = tmp;
        ans += cnt;
    }
    return ans;
}

原文地址:https://www.cnblogs.com/benchao/p/4527074.html