求n的階乘末尾有幾個(gè)零。
注意點(diǎn):
例子:
輸入: n = 5
輸出: 1
通過(guò)因數(shù)分解知道,10是由2和5相乘得到的,而在n的階乘中,因子2的數(shù)目總是比5多的,所以終究末尾有幾個(gè)零取決于其中有幾個(gè)5。1到n中能夠整除5的數(shù)中有1個(gè)5,能整除25的數(shù)有2個(gè)5(且其中1個(gè)在整除5中已計(jì)算過(guò))…所以只要將n不斷除以5后的結(jié)果相加,就能夠得到因子中所有5的數(shù)目,也就得到了終究末尾零的數(shù)目。
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
n //= 5
count += n
return count
if __name__ == "__main__":
assert Solution().trailingZeroes(25) == 6
歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來(lái)取得相干源碼。
上一篇 Java String源碼解析