Leetcode_172_Factorial Trailing Zeroes

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pistolove/article/details/42437049

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42417535


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

Note: Your solution should be in logarithmic time complexity.

思路:

(1)题意为求解一个整数经过阶乘计算得到结果中有多少个0。

(2)我们知道0的个数和2和5有关,而2的个数要远远多于5的个数,所以求得5的个数即为0的个数。

(3)但是对于25、125这样由若干个5相乘组合的,需要计算待求解整数中有多少个这样的数。

(4)例如对于1000来说,1000/5=20,100/25=40,1000/125=8,1000/625=1,1000/1250=0,即0的个数为20+40+8+1=69个。

(5)希望本文对你有所帮助。

算法代码实现如下所示:

public static  int trailingZeroes(int n) {
	int count=0;
	while(n>0){
		count = count + n/5;
		n=n/5;
	}		
	return count;
}


猜你喜欢

转载自blog.csdn.net/pistolove/article/details/42437049