天天看點

lintcode(二):尾部的零 【簡單題】python

描述

設計一個算法,計算出n階乘中尾部零的個數

要求

O(logN)的時間複雜度

思路:

n!中尾部零的個數,即有多少個10相乘 ≡ 2*5 。

而2的指數增長速度比5的指數增長速度要快,故2的個數比5多,隻需要考慮5的個數 tmp=n//5 個,

但是考慮到這 tmp = n//5 個數中,又有5的倍數,還能得到10。故繼續重複上一步的操作:tmp = tmp//5

以下圖為例,來源:https://blog.csdn.net/nwsuaf_uestc/article/details/78788932

lintcode(二):尾部的零 【簡單題】python
class Solution:
    """
    @param: n: An integer
    @return: An integer, denote the number of trailing zeros in n!
    """
    def trailingZeros(self, n):
        # write your code here, try to do it without arithmetic operators.
        count = 0
        tmp = n//5
        
        while tmp != 0 :
            count = count + tmp
            tmp = tmp//5
            
        return count