[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.

給定一個整數n,求n!中有多少個0。

2. 解題思路

n! = 1*2*….*n-1*n,題目要求求一個數的階乘中有多少0,但是真的需要老老實實的把從1乘到n之後再數才能得出n的階乘中0的個數嘛?顯然不是的。要得到一個0,那麼可能的值就是2^n*(5*m),當m=1-4時,可以得到1個0,如15*4=60,m=5時可以得到兩個0,如25*8=100,依次類推,m=5^k時,可以得到k個0。

3. Code

public class Solution {
    public int trailingZeroes(int n) {
        // 2*5 10 4*15 20 8*25 30 ... 100
        int result = 0;
        while(n >= 5)
        {
            // 30的階乘有7個0,5,10,15,20,25(2),30
            result += (int)(n/5);
            n/=5;
        }
        return result;
    }
}
發佈了79 篇原創文章 · 獲贊 58 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章