leetcode-172-阶乘后的零(factorial trailing zeroes)-java

题目及测试

package pid172;
/*阶乘后的零

给定一个整数 n,返回 n! 结果尾数中零的数量。

示例 1:

输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。

示例 2:

输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.

说明: 你算法的时间复杂度应为 O(log n) 。

*/




public class main {
	
	public static void main(String[] args) {
		int[] testTable = new int[]{3,5,7,20};
		for (int ito : testTable) {
			test(ito);
		}
	}
		 
	private static void test(int ito) {
		Solution solution = new Solution();
		int rtn;
		long begin = System.currentTimeMillis();
		
		System.out.print("ito="+ito+" ");		    
		
		System.out.println();
		//开始时打印数组
		
		rtn = solution.trailingZeroes(ito);//执行程序
		long end = System.currentTimeMillis();	
		
		//System.out.println(ito + ": rtn=" + rtn);
		System.out.println( " rtn=" +rtn);
//		for (int i = 0; i < ito.length; i++) {
//		    System.out.print(ito[i]+" ");
//		}//打印结果几数组
		
		System.out.println();
		System.out.println("耗时:" + (end - begin) + "ms");
		System.out.println("-------------------");
	}

}

解法1(成功,1ms,很快)

0=2*5

而阶乘中,有5必有2,所有只要算有几个5就行了

=n/5+n/25+...

还需要得到每个数分解质因子后5的个数

package pid172;

import java.math.BigInteger;

class Solution {
	 public int trailingZeroes(int n) {
		 if(n<=4){
			 return 0;
		 }
	     int now=n/5;
	     int sum=0;
	     while(now>0){
	    	 sum=sum+now;
	    	 now=now/5;
	     }	     		 
		 return sum;
	    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值