JonnyF--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。要求算法复杂度为lg。由于有复杂度的限制,所以就不能采用一般的暴力算法了,因此换个思路来看,要知道什么数相乘直接才会产生0呢?那就是2和5相乘会产生0,那么我们就需要计算这个阶乘中会有几次2*5呢?实际上,只要是偶数那么就会包含2,所以2的出现次数肯定是高于5的,因此只需要计算出较少的那个就好了,那就是计算5出现的次数。注意:25中也是包含5的,因此要对5的倍数进行计算。

class Solution:
    # @return an integer
    def trailingZeroes(self, n):
        res = 0
        while(n):
            res += n/5
            n /= 5
        return res
posted @ 2015-05-14 11:03  F-happy  阅读(108)  评论(0)    收藏  举报