码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode—Factorial Trailing Zeroes

时间:2015-01-28 13:06:21      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode   factorial trailing z   拖尾系数   

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

Note: Your solution should be in logarithmic time complexity.

题目是非常简单的,计算一个数字递归相乘后末尾0的个数

在相乘出现2*5才有可能出现0,2一般是足够的,主要是5的个数,因为是阶乘,比如所以只要数字大于15,那么必定经过15,10,5那么肯定包含3个以上的5,比如25,那么肯定包含25,20,15,10,5,因为25中包含5*5所以还要计算25/5中的5的个数

下面是自己最开始写的方法,虽然运行没有错,但是时间复杂度太大,不好:

int trailingZeroes(int n) {
	if(0 == n)
	{
		return 0;
	}
	int count;
	int src;
	int returnVal = 0;
	while(n)
	{
		src = n;
		count = 0;
		while(!(src%5))
		{
			src = src/5;
			count++;
		}
		returnVal += count;
		n--;
	}
	return returnVal;
}

下面是一些简单的哦算法:
int trailingZeroes(int n) {  
	int res = 0;  
	while(n)  
	{  
		res += n/5;  
		n /= 5;  
	}  
	return res;  
} 

int trailingZeroes(int n) {
    return n < 5 ? 0 : n / 5 + trailingZeroes(n /5);
}


LeetCode—Factorial Trailing Zeroes

标签:leetcode   factorial trailing z   拖尾系数   

原文地址:http://blog.csdn.net/xietingcandice/article/details/43227885

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