leetcode 172. Factorial Trailing Zeroes
2016-04-01 20:56
330 查看
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
题意是计算n!的末尾的0的个数。要求运行时间为对数时间。
先给出最直接的思路:先计算出n! , 然后用n%10依次抽取出末位,并判断是不是0,一旦出现非0则停止计数。显然该方法不满足对数时间要求,且在n=13的时候会内存溢出。
下面思考如何避免直接求出 n! 。可以发现 0 的出现都是由于质数2和5相乘, 理论上统计出对 1:n 进行质因子分解,分别得出2和5的总个数为a,b,取min(a,b)即是0的个数,显然 min(a,b)=b,即5的个数。5的个数可用 floor(n/5) 得到。同时考虑到 25 有 2 个 5 , 125 有 3 个 5,… , 故要对(n/5)进行迭代,直到为 0 。
Note: Your solution should be in logarithmic time complexity.
题意是计算n!的末尾的0的个数。要求运行时间为对数时间。
先给出最直接的思路:先计算出n! , 然后用n%10依次抽取出末位,并判断是不是0,一旦出现非0则停止计数。显然该方法不满足对数时间要求,且在n=13的时候会内存溢出。
class Solution { public: int trailingZeroes(int n) { int q = 1, ans = 0,count=0; for (int i = 2; i <= n; ++i) { ans = q*i; q = ans; } while (ans) { if (!(ans % 10)) ++count; ans /= 10; if (ans%10) break; } return count; } };
下面思考如何避免直接求出 n! 。可以发现 0 的出现都是由于质数2和5相乘, 理论上统计出对 1:n 进行质因子分解,分别得出2和5的总个数为a,b,取min(a,b)即是0的个数,显然 min(a,b)=b,即5的个数。5的个数可用 floor(n/5) 得到。同时考虑到 25 有 2 个 5 , 125 有 3 个 5,… , 故要对(n/5)进行迭代,直到为 0 。
class Solution { public: int trailingZeroes(int n) { int ans=0; while(n){ n/=5; ans+=n; } return ans; } };
相关文章推荐
- rails中使用ajax
- 领域驱动设计(Domain Driven Design)参考架构详解
- leetcode 每日一题 172. Factorial Trailing Zeroes
- tail -F查看线上日志
- Run-Time Check Failure #0 错误
- leetcode 70. Climbing Stairs
- 【HDU】 1023 Train Problem II
- 解决maillog文件删除后无法重建的问题
- opencv_traincascade问题
- AIDL的Binder框架
- 出现( linker command failed with exit code 1)错误总结
- 【HDU】 1022 Train Problem I
- 手动执行failover
- 朴素贝叶斯(naive bayes)
- SendMail发邮件
- RAID技术介绍和总结
- kail新手安装
- 【HDU】 1021 Fibonacci Again
- 游戏AI之行为树(中)
- 游戏AI之行为树(上)