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.
Tags: Math
Similar Problems: (H) Number of Digit Onehtml

2. 解題思路

  • 分解質因子, 當且僅當 因子中出現 一對 (2,5)時, 最後結果會增長一個 trailing zero.
    1. 2的個數永遠多於5個個數.
    2. 計算5的個數時, 最簡單的方法是 SUM(N/5^1, N/5^2, N/5^3...)git

3. 代碼

class Solution {
public:
    int trailingZeroes(int n) 
    { 
        if(n < 1) 
        {
            return 0;
        }
        int nCount = 0;
        while (0 != n/5)
        {
            n = n/5;
            nCount = nCount + n;
        }
        return nCount;
    }
};

4. 反思

參考:http://www.cnblogs.com/ganganloveu/p/4193373.htmlspa

相關文章
相關標籤/搜索