Leetcode 172 Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
A number multiplied by 10
will have a trailing 0
added to it. So we only need to find out how many 10
's will appear in the expression of the factorial. Since 10 = 2 * 5
and there are a bunch more 2
's (each even number will contribute at least one 2
), we only need to count the number of 5
's.
Well, how to count them all? If you try some examples, you may finally get the result, which is n / 5 + n / 25 + n / 125 + ...
.
class Solution: # @param {integer} n # @return {integer} def trailingZeroes(self, n): ans = 0 while n: ans += n / 5 n /= 5 return ans
递归简化版本
class Solution: # @param {integer} n # @return {integer} def trailingZeroes(self, n): return n and n/5 + self.trailingZeroes(n/5)