Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.(您的解决方案应该在对数时间复杂度。)
Note: Your solution should be in logarithmic time complexity.(您的解决方案应该在对数时间复杂度。)
Hide Tags: Math
题目要求:给定N,求N!的末尾有多少0。要求算法复杂度为lg
解题思路:
思路一:
想的比较简单,先实用for循环进行阶乘运算,然后mod10计算0的个数,但是在OJ检查时,超时!,显然是没满足算法时间复杂度为lg的要求。(失败)
代码如下:
public static int trailingZeroes1(int n)
{
int sum=1;
int count=0;
for (int i = n; i >0; i--)
{
sum*=i;
}
while (sum!=0)
{
int remain=sum%10;
if (remain==0)
{
count++;
}
else if (remain!=0)
{
break;
}
sum/=10;
}
return count;
}
思路二(推荐):
只有在2*5的时候才会出现0,其中整十的数也可以看成是2*5的结果,因此,只要在n之间看有多个2,多少个5即可,不难发现2的个数大于5的个数。
因此只需要要记录5的个数即可。但是需要注意的是:像25,125,625之类的数,除以5以后的结果还是5的倍数,所以还需要继续循环处理。
(OJ测试成功)
代码如下:
public static int trailingZeroes(int n)
{
int result=0;
while (n!=0)
{
result=result+n/5;
n/=5;
}
return result;
}