LeetCode:Factorial Trailing Zeroes
2015-11-19 22:08
344 查看
Factorial Trailing Zeroes
Total Accepted: 42370 TotalSubmissions: 139281 Difficulty: Easy
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
1.求n!中后缀0的个数。
2.n!后缀0的个数由(2^i)*(5^j)得来。
3.因此,要求min(i,j)。
4.j<=i,直观的来看i是逢2进1,j是逢5进1。因此,min(i,j)==j。
5.即求n!能被5整除的个数,即k=n/5 + n/25 + n/125 + ... + n/(2^j),其中j<=n。
代码:
class Solution { public: int trailingZeroes(int n) { int x = 5; int ret = 0; while(x <= n) { ret += n/x; x *= 5; } return ret; } };
或:
class Solution { public: int trailingZeroes(int n) { int ret = 0; while(n) { ret += n/5; n /= 5; } return ret; } };
相关文章推荐
- TIME_WAIT状态(2MSL)的作用
- Container Water | LeetCode
- 【leetcode】Contains Duplicate
- PAT-PAT (Advanced Level) Practise Highest Price in Supply Chain(25) 【三星级】
- 【Linux学习笔记】栈与函数调用惯例 http://blog.csdn.net/xiaogugood/article/details/38490663
- Linux内核地址映射模型 http://blog.csdn.net/f22jay/article/details/7925531
- 编译遇到“__stack_chk_fail_local”错误
- [__NSCFString containsString:]: unrecognized selector sent to instance 的解决方案
- 人工智能中的具体搜索方法
- HOJ Train Problem II
- 栈区,堆区,全局区:内存结构图 http://blog.csdn.net/xlf13872135090/article/details/8828704
- 多线程 - 你知道线程栈吗 http://blog.csdn.net/gykimo/article/details/9132157
- 进程线程及堆栈关系的总结 http://blog.csdn.net/echoisland/article/details/6403763
- Daily Scrum - 11/19
- lightoj 1236 pairs of lcm
- POJ - 1422 Air Raid(DAG的最小路径覆盖数)
- 分类算法之朴素贝叶斯分类(Naive Bayesian classification)
- larave 5 could not be opened: failed to open stream: Permission denied
- STL Container和ATL智能包裹类的冲突
- LightOJ 1021 Painful Base(状压DP)