LeetCode Factorial Trailing Zeroes
2016-05-29 21:39
495 查看
LeetCode解题之Factorial Trailing Zeroes
原题
求n的阶乘末尾有几个零。注意点:
将时间复杂度控制为log(n)
例子:
输入: n = 5
输出: 1
解题思路
通过因数分解知道,10是由2和5相乘得到的,而在n的阶乘中,因子2的数目总是比5多的,所以最终末尾有几个零取决于其中有几个5。1到n中能够整除5的数中有一个5,能整除25的数有2个5(且其中一个在整除5中已经计算过)…所以只要将n不断除以5后的结果相加,就可以得到因子中所有5的数目,也就得到了最终末尾零的数目。AC源码
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) 来获得相关源码。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法