【E】【87】【leetcode】Factorial Trailing Zeroes

175 篇文章 0 订阅
157 篇文章 0 订阅

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

不得不说这道题太经典,因为它逼着你去优化

算一个数的阶乘,结尾有多少0

小学奥数,就是算因子2和5有多少个

而2肯定比5多,所以只需要算5有多少个

最开始是对每个数,除以五那样算,到一个很大的数的时候,超时了

这样就得想怎么优化。

对一个数n,它肯定有 n/5 个5,
这样没数全,还得看25,125……等等

所以,直接优化成这样
</pre></div><div><span style="font-size: 14px;"><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;"><span style="color: rgb(51, 51, 51);"></span></span></span><pre name="code" class="html"><span style="white-space:pre">	</span>num_5 = 0
        while n>0:
            n /= 5
            num_5 += n



后来发现可以递归:
return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)





class Solution(object):
    def trailingZeroes(self, n):
        #return 0 if n == 0 else n / 5 + self.trailingZeroes(n / 5)
        num_5 = 0
        while n>0:
            n /= 5
            num_5 += n
        '''
        for i in xrange(1,n+1):
            #print i,
            while i > 1 and i % 5 == 0:
                if  i!= 0:
                    num_5 += 1
                    i /= 5
        '''
        return num_5
        """
        :type n: int
        :rtype: int
        """
       


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值