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

Java for LeetCode 172 Factorial Trailing Zeroes

时间:2015-06-06 07:56:09      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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

Note: Your solution should be in logarithmic time complexity.

解题思路:

计算n能达到的5的最大次幂,算出在这种情况下能提供的5的个数,然后减去之后递归即可,JAVA实现如下:

	static public int trailingZeroes(int n) {
		if(n<25)
			return n/5;
		long five=5;
		int count=0;
		while(n>=five){
			five*=5;
			count++;
		}
		int temp=(int) (n/Math.pow(5, count));
		return countSum(count)*temp+trailingZeroes(n-temp*(int)Math.pow(5, count));
	}
	static public int countSum(int count){
		if(count==1)
			return 1;
		else return countSum(count-1)*5+1;
	}

 

Java for LeetCode 172 Factorial Trailing Zeroes

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4555912.html

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