172. Factorial Trailing Zeroes [easy] (Python)

题目链接

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

题目原文

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

Note: Your solution should be in logarithmic time complexity.

题目翻译

给定一个整数n,返回n!尾部0的个数。你的解法的时间复杂度要控制在O(logn)。

思路方法

所有的尾部的0可以看做都是2*5得来的,所以通过计算所有的因子中2和5的个数就可以知道尾部0的个数。实际上,2的个数肯定是足够的,所以只需计算5的个数即可。
要注意,25=5*5是有两个5的因子;125=5*5*5有3个5的因子。比如,计算135!末尾0的个数。
首先135/5 = 27,说明135以内有27个5的倍数;27/5=5,说明135以内有5个25的倍数;5/5=1,说明135以内有1个125的倍数。当然其中有重复计数,算下来135以内因子5的个数为27+5+1=33。

思路一

迭代求解。

代码

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

思路二

递归求解。

代码

class Solution(object):
    def trailingZeroes(self, n):
        """
        :type n: int
        :rtype: int
        """
        return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51590478

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值