[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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章