【Leetcode_总结】 172. 阶乘后的零

Q:

给定一个整数 n,返回 n! 结果尾数中零的数量。

示例 1:

输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:

输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.

说明: 你算法的时间复杂度应为 O(log n) 


首先,时间复杂度应为 O(log n) ,就说明会有比较大的数字出现,先暴力求解试一下,方法如下,递归计算一个阶乘,然后从后面开始数0 返回答案,显而易见

【超时】

class Solution:
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        strs = str(self.f(n))
        print(strs)
        right = len(strs)-1
        count = 0
        if strs[right] == "0":
            while (right > 0):
                if strs[right] == "0":
                    count += 1
                    right -= 1
                else:
                    return count
        else:
            return 0

    def f(self,n):
        if n == 0:
            return 1
        else:
            return n*self.f(n-1)

没有想到什么好的办法,所以参考了一下别人的代码,如下:


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

还是找规律吧~

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/83176209