码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode——172 Factorial Trailing Zeroes(N!尾巴上有多少个0,算法复杂度为lg)

时间:2015-06-19 10:27:59      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   java   阶乘运算   

Given an integer n, return the number of trailing zeroes in n!.

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;
	}

leetcode——172 Factorial Trailing Zeroes(N!尾巴上有多少个0,算法复杂度为lg)

标签:leetcode   算法   java   阶乘运算   

原文地址:http://blog.csdn.net/zzc8265020/article/details/46558363

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!