Wednesday, March 13, 2019

LeetCode 172. Factorial Trailing Zeroes

'''
Given an integer n, return the number of trailing zeroes in n!.
'''
class Solution:
    #seems working, but exceeds time
    def trailingZeroes1(self, n: int) -> int:
        if n == 0: return 0
        count = 0
        i = 1
        while i <= n:
            temp = i
            while temp % 10 == 0 or temp % 10 == 5:
                count += 1
                temp /= 5
            i += 1
        return count
   
    #improve from the above methods
    #60ms, 13.1MB
    def trailingZeroes(self, n: int) -> int:
        if n == 0: return 0
       
        count = 0
        i = 1
        #obtain min count for 5^count > n
        while i <= n:
            i *= 5
            count += n//i
       
        return count

No comments:

Post a Comment