题目
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
总结
计算n中含有5的个数,25(5*5)的个数,125(5*5*5)的个数。因为25可以拆分为5*5,和偶数相乘可以得到2个0,并且偶数总是足够的,题此类推
代码:
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
if n != 0:
return n // 5 + self.trailingZeroes(n // 5)
return 0
非递归代码:
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
total = 0
while n > 0:
total += n // 5
n = n // 5
return total