程序员面试金典——17.3阶乘尾零

程序员面试金典——17.3阶乘尾零

Solution1:我的答案。没有更笨的方法了。。。

class Factor {
public:
    int getFactorSuffixZero(int n) {
        // write code here
        int nums_2 = 0, nums_5 = 0;
        for(int i = 1; i <= n; i++) {
            nums_2 += nums_of_2(i);
            nums_5 += nums_of_5(i);
        }
        return min(nums_2, nums_5);
    }

    int nums_of_2(int n) {
        int res = 0;
        while(n%2 == 0) {
            res++;
            n /= 2;
        }
        return res;
    }

    int nums_of_5(int n) {
        int res = 0;
        while(n%5 == 0) {
            res++;
            n /= 5;
        }
        return res;
    }
};

Solution2:
参考网址:https://www.nowcoder.com/profile/9993586/codeBookDetail?submissionId=14652823
考虑进了概率的因素,大大降低了复杂度,好啊~~~

/*
 * 思路:刚开始做这道题的时候,我是先求出n!再计算有多少个0
 * 这样的复杂度很大,编译不通过,后来在编程之美中看到了思路,思路如下
 *   n!可以质因数分解,由于2*5=10,所以尾零的个数只与2和5有关
 *   但是能被2整除的频率比被5整除的数高的多,所以尾零的个数其实只和5相关,
 *   n!能被多少个5解,就有多少个0,
 *   这事,通过遍历(1到n)只要将能被5整除,就统计+1,最后统计的数,就是尾零的个数
 *
 */
public class Factor {
      public int getFactorSuffixZero(int n) {
          int count=0;
          for (int i = 1; i <=n; i++) {
              int j = i;
            while(j%5==0){
                count++;
                j/=5;
            }
        }
          return count;
      }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值