[leetcode]Factorial Trailing Zeroes

题目描述如下:

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

Note: Your solution should be in logarithmic time complexity

就是就N阶乘的末尾有几个0。第一遍的代码没有看题目Note的部分直接写了一个巨丑陋的代码结果TLE了…这里就不放那个代码了,实在是有些见不得…

其实思路大家都会想到的,就是求阶乘的书中最后能分解出几个2和几个5,又因为在指数型关系下5的个数的增长速度会明显更慢,因此就是求5的个数。

在1-N这N个数中,如果该数仅为5的倍数则贡献1,若为25的倍数则贡献2。而1-N中,5的倍数个数为|N/5|(|_ |表示取下整数)。又因为在1-N中,25的倍数个数为|_N/25|.需要注意到的是|N/5|已经包含了|N/25|,考虑到避免重复计算,则N!的素数分解中5的指数j为:j = |N/5|+|N/25|+|N/5^3|+…。因此,用一个循环便可以解决,代码如下:

public class Solution {
   public int trailingZeroes(int n) {
        if(n < 5) return 0;     // 包含了n小于0的情况
        int ZeroNum = 0, tmp;
        tmp = n;
        while(tmp != 0){
            ZeroNum += tmp / 5;
            tmp /= 5;
        }
        return ZeroNum;
    }
}

题目链接:https://leetcode.com/problems/factorial-trailing-zeroes/

你可能感兴趣的:([leetcode]Factorial Trailing Zeroes)