LeetCode—Factorial Trailing Zeroes

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值