求n的階乘末尾有幾個零。
注意點:
例子:
輸入: n = 5
輸出: 1
通過因數分解知道,10是由2和5相乘得到的,而在n的階乘中,因子2的數目總是比5多的,所以終究末尾有幾個零取決于其中有幾個5。1到n中能夠整除5的數中有1個5,能整除25的數有2個5(且其中1個在整除5中已計算過)…所以只要將n不斷除以5后的結果相加,就能夠得到因子中所有5的數目,也就得到了終究末尾零的數目。
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) 來取得相干源碼。
上一篇 Java String源碼解析
下一篇 尼瑪,Timer也會休眠啊。