本文共 452 字,大约阅读时间需要 1 分钟。
题目描述:
给定一个数n
,返回n
的阶乘中末尾0
的个数。比如: zeros(6) = 1# 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zerozeros(12) = 2# 12! = 479001600 --> 2 trailing zeros
代码如下:在这里不能够求阶乘,因此如果n
很大的会溢出,计算量很大,因此需要通过查找结果的规律来求解。
0
的情况是从1
到n
中有数字相乘为10 或10的倍数,也就是存在2*5=10,在数字中5的倍数出现的几率减少。 因此只需要统计出对1到n
中所有数因子分解后得到的5的个数即可。 def zeros(n): temp = 0 while n: temp += n // 5 n = n // 5 return temp
转载地址:http://cqmws.baihongyu.com/