python小课——零基础入门——学习笔记刷题学编程Leetcode模拟面试

LeetCode 172. 阶乘后的零

2021-09-13  本文已影响0人  freesan44

题目

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

示例 1:

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

输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。

解题思路

class Solution:
    def trailingZeroes(self, n: int) -> int:
        # ## 暴力解法
        # res = 1
        # for i in range(1,n+1):
        #     res *= i
        #     # print(res, i)
        # # print(res)
        # resStr = list(str(res))
        # resCount = 0
        # while resStr.pop() == "0":
        #     resCount += 1
        # return resCount
        #根据5因子进行除法得出
        res = 0
        while n >= 5:
            n //= 5
            res += n
        return res

if __name__ == '__main__':
    nums = 20
    result = Solution().trailingZeroes(nums)
    print(result)
上一篇 下一篇

猜你喜欢

热点阅读