【题目描述】
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
【思路】看n的阶乘里有多少个0,只要看1~n中有多少个2和5就可以了,又因为2肯定比5多,所以只要看5有多少个就可以了。另外,还要注意像25里包含了2个5,125里包含了3个5.。。
【代码】
class Solution {
public:
int trailingZeroes(int n) {
int ans=0;
while(n){
ans+=n/5;
n=n/5;
}
return ans;
}
};
本文介绍了一种高效算法,用于计算给定整数n的阶乘中尾部0的数量。该算法通过统计1到n范围内包含因数5的个数来实现,采用循环除以5的方式,并考虑了如25、125等特殊情况下额外的5的倍数。
512

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



