172. Factorial Trailing Zeroes

1.描述

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

Note: Your solution should be in logarithmic time complexity.

2.分析

求n!后面有多少个0,实际上是求1、2、3、……、n公约数中有多少对2和5。
由于2的个数明显大于5的个数,从而可以转化为求1到n的公约数中有多少个5。
注意:5的x次方可能超过int的最大值,因此需要使用long long类型。

3.代码

int trailingZeroes(int n) {
    if (n < 5) return 0;
    unsigned int zeroes = 0;
    long long fives = 5;
    while (n / fives >=1) {
        zeroes += n / fives;
        fives *= 5;
    }
    return zeroes;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容