Factorial Trailing Zeroes


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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

public class Solution {

    public int trailingZeroes(int n) {

        int result=1;


for(int i=1;i<=n;i++){


if ((i%5==0)||(i%10== 0)) result++;


}

return result;

    }

}


问题:给你一个整数n。返回n!的尾部的零的个数。

Note:算法的时间复杂度应该是对数级的

分析:

阶乘的结果的最后0的个数,5*一个偶数结尾为0. 10*任意数,结尾为0.

而5一定能遇到足够多的偶数来组成0,

所以就只需要统计1-n中,结尾为5和0的个数。

public class Solution {

    public int trailingZeroes(int n) {

        int result=1;


for(int i=1;i<=n;i++){


if ((i%5==0)||(i%10== 0)) result++;


}

return result;

    }

}


但是该解法的时间复杂度为O(N)。
给定一个N,那么其中1-N中是10的倍数的数的个数应该为N/10
5的倍数的数的个数应该为N/5.(但该数目包含了整除10的个数)
所以只跟5的整数倍的数个个数有关。
所以初步判断返回n/5就可以了。
比如11,则有5和10贡献2个0. 所以返回11/5 =2.
但是
注意:
对于25来说,其为5*5,提供2个5.
比如26:5,10,15,20,各贡献1个0,但是25贡献2个。
所以一共6个0 而不是5个。
最终算法:

result=n/5
如果n/5>5,

result +=(n/5)/5. 重复下去

public static int trailingZeroes(int n) {

int count = 0;

while (n / 5 >= 1) {

count += n / 5;

n /= 5;

}

return count;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值