leetcode 172 Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.python

Note: Your solution should be in logarithmic time complexity.markdown

解決思路:
決定階乘末尾零的個數實際上是數列中5出現的次數,好比5的階乘一個零。1024的階乘末尾到底有幾個零呢?spa

http://bbs.csdn.net/topics/380161955.net

這裏寫圖片描述
代碼以下:code

int trailingZeroes(int n) 
{
    int total = 0;

    while(n>=5)
    {
        n = (n-(n%5))/5;
        total = total + n;
    }

    return total;

}

python 的解決方案:圖片

class Solution:
    # @return an integer
    def trailingZeroes(self, n):
        factor, count = 5, 0

        while True:
            curCount = n // factor
            if not curCount:
                break

            count += curCount
            factor *= 5

        return count
相關文章
相關標籤/搜索