Very Simple Python3 Solution

  • 0

    Approach #1 Brute Force
    We can calculate the factorial and count the number of trailing zeros. But it's very slow.

    Approach #2 Implementation
    By taking a simple analysis we can find out that the number of trailing zeros of n! depends on how many 10s can be made during the factorial calculation. Since 10 = 2 * 5 and the number of 2 in a factorial is more than that of 5, we can simplify this problem to "how many 5s are contained in n". For example, n = 4. Since 4 contains none of 5, so the number of trailing zeros of 4! will be 4 // 5 = 0; if n = 5, 5 contains one 5, so the trailing zeros of 5! will be 5 // 5 = 1, and so on. By knowing this, we can divide n by 5 for each time until it turns to 0 and add each quotient to the final result.

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

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.