Factorial Trailing Zeroes

来源:互联网 发布:电子罗盘软件下载 编辑:程序博客网 时间:2024/06/07 00:03

https://oj.leetcode.com/problems/factorial-trailing-zeroes/

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

Note: Your solution should be in logarithmic time complexity.

public int trailingZeroes(int n)


这一题其实换一种说法就是求这个n的阶乘里面可以被5的k次方整除,k的最大值是多少。

首先建立一种想法,就是1~n里面,有多少个5的倍数。譬如1~10中有两个5的倍数,所以10的阶乘就有两个0。所以第一阶段的答案是n / 5

然而实际上25,50,75....这样的实际上相当于两个5相乘。所以我们第二阶段的答案是n / 25

如此类推,包括5的三次方的倍数,四次方的倍数....


所以实际上我们要求的就是n / Math.pow(5, i) i = 1....m 的累积和, 其中Math.pow(5, m + 1)刚好大于n

于是乎算法已经出来了。根据算法,给出代码如下:

    public int trailingZeroes(int n) {        int res = 0;        long div = 5;while((long)n >= div){    res += (int)((long)n / div);    div *= 5;}return res;    }

这里之所以用long是防止case比较极端,Math.pow(5, m + 1)超出了整型数范围。所以其实换过来还有另一种写法:

    public int trailingZeroes(int n) {        int res = 0;while(n >= 5){n /= 5;res += n;}return res;    }

这里可以这么理解:n / 25 和 n 除以5再除以5是一样的。所以我们就可以换成这么写,不用long也不需要担心溢出问题。

0 0
原创粉丝点击