【每日一题20220731】阶乘后的零

题目难度:中等
题目来源:172. 阶乘后的零 - 力扣(LeetCode)

描述

:mage:‍给定一个整数 n ,返回 n! 结果中尾随零的数量。
备注: n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1

编写一个函数, 完成上述操作

class Solution:
    def trailingZeroes(self, n: int) -> int:
    # your code here

示例 1:

输入:n = 3
输出:0
解释:3! = 6 ,不含尾随 0

示例 2:

输入:n = 5
输出:1
解释:5! = 120 ,有一个尾随 0

示例 3:

输入:n = 0
输出:0

提示:

  • 0 <= n <= 104

:+1:

先来个最耗时的 :joy:

def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        re = n
        m = 1
        for i in range(n):
            if re<=0:
                break
            m*=re
            re-=1
        last = str(m)
        sum = 0
        for i in last[-1::-1]:
            if i!="0" :
                return sum
            sum+=1

面向答案编程

:joy:

class Solution:
    def trailingZeroes(self, n: int) -> int:
        x=1
        for i in range(1,n+1):
            x*=i
        s=0
        for j in range(len(str(x)),0,-1):
            if str(x)[j-1]=='0':
                s+=1
            else:
                break
        return s

assert Solution().trailingZeroes(5)==1
assert Solution().trailingZeroes(3)==0
assert Solution().trailingZeroes(0)==0