LeetCode172:Factorial Trailing Zeroes
2015-06-07 15:09
369 查看
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity.
这道题需要在对数时间内求解阶乘中尾端0的个数。
阶乘中0的个数是由各项因子中2和5的个数决定的,又由于阶乘是连续n的数的积,所以2的数目比5的数目多,故0的个数就等于各项因子中5的个数。
以10!为例分析:
10!=10*9*8*7*6*5*4*3*2*1
包含因子2的数有5个,10=2*5,8=2*4,6=2*3,4=2*2,2=2*1
其中除以2后剩下的5个数分别为5,4,3,2,1,依然存在包含2的数为4,2,
除以2后依然存在一个包含2的数2
这样10!中包含2的个数是【10/2】+【10/2^2】+【10/2^3】=5+2+1
注:【num】表示不大于num的最大的整数
也可以用同样的方式求5的因子的个数,而这道题就是求5的因子的个数。
runtime:3ms
class Solution { public: int trailingZeroes(int n) { int result=0; while(n>=5) { result+=n/5; n/=5; } return result; } };
相关文章推荐
- Climbing Stairs
- hdu 1104 Remainder 队列
- hdu 1104 Remainder 队列
- xiugaicrontab默认编辑器
- HDU 5240 E - Exam(2015 ACM-ICPC China Shanghai Metropolitan Programming Contest)
- BZOJ 1664: [Usaco2006 Open]County Fair Events 参加节日庆祝( dp )
- poj 1273 Drainage Ditches 【最大流入门 dinic算法】
- NOI2011阿狸的打字机(fail树+DFS序)
- 【转】Ubuntu安装ARM架构GCC工具链(ubuntu install ARM toolchain)最简单办法
- LeetCode Contains Duplicate III
- 使用ssh框架时出现 failed to lazily initialize 或者 no session 异常
- 人工智能搜索算法(深度优先、迭代加深、一致代价、A*搜索)
- URAL 1457. Heating Main
- Contains Duplicate
- 如何在 Ubuntu 中更改默认浏览器和 Email 客户端
- ISP Pipeline的关键模块之Demosaic( 三)
- LeetCode Contains Duplicate II
- Aizu 0005
- 错误 1 error LNK2019: 无法解析的外部符号 "public: __thiscall chain<int>::~chain<int>(void)" (??1?$chain@H@@QAE@
- rails使用devise验证