首页 > 技术文章 > Random随机类(11选5彩票)BigInteger大数据类(华为面试题1000的阶乘)

void-m 2016-12-29 16:45 原文

先上Java Web图

 

为了简化叙述,只写Java代码,然后控制台输出

使用【Random类】取得随机数

import java.util.Random;

public class Fir {
	public static void main(String[] args) {
		//输出
		int [] a=creatnumber_11x5();
		for(int i=0;i<a.length;i++){
			System.out.print(a[i]+"  ");
		}
	}
	//11选5 也可以实现36选7
	public static int[] creatnumber_11x5() {
		Random rd=new Random();
		//11选5
		int MEM=5,TOT=12;
		int [] number=new int[MEM];
		for(int i=0;i<MEM;i++){
			boolean flag=true;
			while(flag){
				int a=rd.nextInt(TOT);
				if(isRe(number,a)){
					number[i]=a;
					flag=false;
				}
			}
		}
		//冒泡排序
		int temp=0;
		for(int i=1;i<number.length;i++){
			for(int j=0;j<number.length-i;j++){
				if(number[j]>number[j+1]){
					temp=number[j];
					number[j]=number[j+1];
					number[j+1]=temp;
				}
			}
		}
		return number;
	}
	/**
	 * 判断是否重复
	 * @param arr
	 * @param x
	 * @return
	 */
	public static boolean isRe(int[] arr,int x){
		for(int i=0;i<arr.length;i++){
			if(x==arr[i]){
				return false;
			}
		}
		return true;
	}
}

BigInteger大数据了  

构造函数public BigInteger(String str)

也就是接受字符串类型

示例:

		BigInteger b1=new BigInteger("4953493636435253464646");
		BigInteger b2=new BigInteger("5685639769376446");
		System.out.println(b1.add(b2));
		System.out.println(b1.subtract(b2));
		System.out.println(b1.multiply(b2));
		System.out.println(b1.divide(b2));

  

除法小数位被被截断
divideAndRemainder()此函数处理小数
返回一个数组,索引0存储整数,索引1存储小数

public class Te {
	public static void main(String[] args) {
		BigInteger b1=new BigInteger("4953493636435253464646");
		BigInteger b2=new BigInteger("5685639769376446");
		System.out.println(b1.add(b2));
		System.out.println(b1.subtract(b2));
		System.out.println(b1.multiply(b2));
		System.out.println(b1.divide(b2));
		
		//除法小数位被被截断
		BigInteger[] b=b1.divideAndRemainder(b2);//此函数处理小数
		//返回一个数组,索引0存储整数,索引1存储小数
		System.out.println(b[0]);
		System.out.println(b[1]);
	}
}

  来看华为的一道面试题:求1000的阶乘。

此题设计的非常能区分人

如果只是考虑一个for循环连续相乘,出错还找不到原因,那基本水平可以测试出来。

1、此题起码需要了解底层一些知识:

存储的结果用int保存?long保存?long64位最多保存的数也有范围,超出了怎么办?

2、有数学的观察力:1000看似小,但是经过连乘这个数大概是多少位?

3、如何保存计算结果。

此题的一种解法是,用int数组来保存每一位整数,然后每10进位

用Java中的BigInteger类工具可以轻松解决此问题

 

import java.math.BigInteger;

public class TT {
	public static void main(String[] args) {
		
		//求1000的阶乘
		BigInteger bigIn=new BigInteger("1");
		for(int i=1;i<1000;i++){
			BigInteger currentBigInte=new BigInteger(""+i);
			bigIn=bigIn.multiply(currentBigInte);
		}
		System.out.println(bigIn);
	}
}

为了更好观察,切刀cmd下运行  

运行如图:

 

推荐阅读