您的位置:首页 > 大数据 > 人工智能

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的时候会内存溢出。

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: