题目链接:172. 阶乘后的零
朴素解法,考虑 python 的整型是无界的,可以直接计算。
class Solution:
def trailingZeroes(self, n: int) -> int:
ans = 1
for i in range(1, n + 1):
ans *= i
return len(str(ans)) - len(str(ans).rstrip('0'))
但是正常情况下必须要考虑阶乘溢出。
计算末尾 $0$ 的数量,其实就是计算 $n!$ 里面有多少个 $10$。更具体地,在对 $n!$ 进行因数分解后,其中有多少个 $5 \times 2$。因为因数分解后, $5$ 的数量肯定比 $2$ 多,所以就是寻找对 $n!$ 进行因数分解后,其中有多少个 $5$。
class Solution:
def trailingZeroes(self, n: int) -> int:
count = 0
while n > 0:
count += n // 5
n //= 5
return count