Tuesday, August 25, 2015

Leetcode 172. Factorial Trailing Zeroes

https://leetcode.com/problems/factorial-trailing-zeroes/

We know that 2 x 5 =10 is the source of trailing zeroes. So do we need to count the numbers of 2 and 5 in the factorial? Actually no. Because when one 5 occurred, two 2 have occurred. Hence we only need to count the number of 5, for 2 must be more.

Solution:
# T:O(lgn) S:O(1)
class Solution:
    # @return an integer
    def trailingZeroes(self, n):
        result = 0
        while n > 0:
            result += n / 5
            n /= 5
        return result
Run Time: 52 ms

No comments:

Post a Comment