`

java算法----求解N的阶乘的结果中从个位开始连续的0的个数

    博客分类:
  • java
 
阅读更多
package com.zhonghaiwangluokeji.interview;

/**
 * 求N!的阶乘的结果的末尾有多少个连续的0
 * @author yangjianzhou
 * 实现原理:这个阶乘分解因式后有多少个5,例如25=5*5.
 * 任何一个偶数与5的乘积的结果个位一定为0
 * 
 */
public class Problem2 {

	public static void main(String[] args) {
		System.out.println(countZeros(1000));
		System.out.println(zeroCount(1000));
	}
	/**
	 * 网上例子
	 * @param n
	 * @return
	 */
	static int zeroCount ( int n) {  
		int counter = 0;  
		for( int i = 5,m; i <= n; i += 5) {  
			m = i;  
			while ( m % 5 == 0) {  
				counter++;  
				m /= 5;  
			}  
		}  
		return counter;  
	}  

	/**
	 * 自己实现
	 * @param n
	 * @return
	 */
	public static int countZeros(int n){

		int start = 5;
		int count = 0;
		int temp;

		while(start<=n){
			temp = start;
			while(temp%5==0){
				temp = temp/5;
				count ++;
			}
			start = start+5;
		}
		return count;
	}
}



运算结果:
249
249
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics