zoukankan      html  css  js  c++  java
  • 阶乘末尾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;
    }

  • 相关阅读:
    MySQL操作表中的数据
    mysql查询语句进阶
    mysql基本查询语句
    mysql函数
    mysql约束
    操作MySQL表
    操作MySQL数据库
    mysql视图
    as2 播放停止音效
    as3 深复制
  • 原文地址:https://www.cnblogs.com/benchao/p/4527074.html
Copyright © 2011-2022 走看看