Java BigInteger的使用
特点
BigInteger支持任意精度的整数运算(范围为无穷大)
方法
-
读入一个BigInteger
Scanner scanner = new Scanner(System.in); //读入一个Int作为对比 int example_int = scanner.nextInt(); //读入一个BigInteger BigInteger bigInteger = scanner.nextBigInteger();
-
构造一个BigInteger
//把 radix 进制的字符串 构造为 BigInteger String str = "101110011101001001"; int radix = 2; BigInteger bigInt = new BigInteger(str,radix); //一个二进制数的转化 //如果没有radix 参数,则默认转化为十进制 BigInteger bigInt2 = new BigInteger("124124813579235");
-
基本运算
BigInteger a = new BigInteger("123"); BigInteger b = new BigInteger("3124"); int n = 3; //加运算 : add BigInteger outcome_add = a.add(b); //减运算 : subtract BigInteger outcome_subtract = a.subtract(b); //乘运算 : multiply BigInteger outcome_multiply = a.multiply(b); //除运算 : divide BigInteger outcome_divide = a.divide(b); //取模运算;mod BigInteger outcome_mod = a.mod(b); //求余运算 : remainder BigInteger outcome_remainder = a.remainder(b); //次方运算 : pow BigInteger outcome_pow = a.pow(n); //取绝对值 :abs BigInteger outcome_abs = a.abs(); //取相反数 :negate BigInteger outcome_negate = a.negate(); //大小比较 //1.compareTo() :返回int 1 大于 0 等于 -1 小于 int outcome = a.compareTo(b); //2.max()返回较大值 int outcome1 = a.max(b); //3.min()返回较小值 int outcome2 = a.min(b);
-
类型转化
BinInteger bigNum = new BigInteger("1232141241"); //二进制补码转换 byte[] num1 = bigNum.toByteArray(); //十进制字符串转换 String num2 = bigNum.toString(); //radix进制字符串转化(默认为十进制) int radix = 8; //八进制 String num3 = bigNum.toString(radix); //int转换 int num4 = bigNum.intValue(); //long转换 int num5 = bigNum.longValue(); //float转换 int num6 = bigNum.floatValue(); //double转换 int num7 = bigNum.doubleValue();