172. Factorial Trailing Zeroes

2017-06-15  本文已影响0人  Leorio_c187

题目

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

Note: Your solution should be in logarithmic time complexity.

思路

Python

递归

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        #A very smart question, 2 is always ample, so we only need to care about the factor of 5
        return  0 if n == 0 else n/5 + self.trailingZeroes(n/5)
       

循环

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        #A very smart question, 2 is always ample, so we only need to care about the factor of 5
        res = 0
        while n > 0:
            n /= 5
            res += n
        return res
       
上一篇 下一篇

猜你喜欢

热点阅读