LintCode_2_尾部的零

设计一个算法,计算出n阶乘中尾部零的个数

样例

11! = 39916800,因此应该返回 2

挑战 

O(logN)的时间复杂度

自然的就想到产生0的有2*5一个0,4*25两个0,8*125三个0,所以只需要算有多少能整除5及5的次方数,再根据这个算阶乘最后0的数目,所以自己写出来的代码是这样

class Solution {
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        write your code here
        long ans = 0;
        long i = 0;
        while((long)Math.pow(5,i) <= n){
            i++;
        }
        for(long j = 1; j < i; j++){
            ans+=n/((long)Math.pow(5,j));
        }
        return ans;
    }
};
然后搜了一下发现不用这么麻烦,因为4*25本质也是可以看作2*5*2*5,所以只需要对第一次整除5后的数继续整除5,直到除不尽。所以代码变成了

class Solution {
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) {
        long ans = 0;
        while(n > 0){
            ans += n/5;
            n/=5;
        }
        return ans;
    }
};

果然简单易懂了不少。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值