Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路:大意是求n!的末尾有多少个0,可以想到要在末尾产生0,就必须有10才行,10=5*2,在阶乘中不缺2,那么这个问题就变成了在这个阶乘中有多少个5的问题
代码:
class Solution {
public:
int trailingZeroes(int n) {
int ans=0;
while(n){
ans+=(n/5);
n/=5;
}
return ans;
}
};
本文介绍了一种高效算法,用于计算给定整数n的阶乘末尾有多少个零。通过分析发现只需关注阶乘中5的倍数即可,并提供了一个运行时间为对数级别的解决方案。
509

被折叠的 条评论
为什么被折叠?



