1. 程式人生 > >LeetCode演算法題172:階乘後的零解析

LeetCode演算法題172:階乘後的零解析

給定一個整數 n,返回 n! 結果尾數中零的數量。
示例1:

輸入: 3
輸出: 0
解釋: 3! = 6, 尾數中沒有零。

示例2:

輸入: 5
輸出: 1
解釋: 5! = 120, 尾數中有 1 個零.

說明: 你演算法的時間複雜度應為 O(log n) 。

這個題不太好想,可能需要記住,出現尾數為0,那麼一定是出現了25這樣的數對,那就是說出現了多少25就有多少個0,很明顯直接找5就好,因為5的倍數一定比2的倍數少,所以出現的5及其倍數的個數就是尾數零的個數,但是需要考慮的是遇到25、125這類數是可以分解出不止一個5的,所以程式中稍微做了一點操作使得這種可以計算所有5.
C++原始碼:

class Solution {
public:
    int trailingZeroes(int n) {
        int result = 0;
        while (n)
        {
            result += n / 5;
            n = n / 5;
        }
        return result;
    }
};

python3原始碼:

class Solution:
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
result = 0 while n: result += n // 5 n = n // 5 return result