1. 程式人生 > >【Leetcode_總結】 172. 階乘後的零

【Leetcode_總結】 172. 階乘後的零

Q:

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

示例 1:

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

示例 2:

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

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

首先,時間複雜度應為 O(log n) ,就說明會有比較大的數字出現,先暴力求解試一下,方法如下,遞迴計算一個階乘,然後從後面開始數0 返回答案,顯而易見

【超時】

class Solution:
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        strs = str(self.f(n))
        print(strs)
        right = len(strs)-1
        count = 0
        if strs[right] == "0":
            while (right > 0):
                if strs[right] == "0":
                    count += 1
                    right -= 1
                else:
                    return count
        else:
            return 0

    def f(self,n):
        if n == 0:
            return 1
        else:
            return n*self.f(n-1)

沒有想到什麼好的辦法,所以參考了一下別人的程式碼,如下:

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

還是找規律吧~