这篇来了解和学习一下BigInteger类,我记得在Oracle面试的时候,被问过这个知识点。大致的问题就是,给两个很大的数,int类型存储不下,如何进行两个很大数的相减。当时的回答是,把这个字符串转成字符串数组,然后没一个位进行相减,但是不知道如何处理,位数不够如何向前接一个的问题,代码写不出来。如果当时知道有BigInteger类,就很容易实现。
1.API阅读BigInteger类的基本介绍
如果发现一个int类型存储不了的情况(定义一个12位数的数字赋值给int变量会报错),就可以考虑BigInteger,在BigInteger有一个构造方法的参数传入的是一个字符串。
2.代码实现BigInteger加减乘除
使用加减乘除运算,返回的值还是BigInteger对象。
package otherclass;
import java.math.BigInteger;
public class Demo1_System {
public static void main(String[] args) {
BigInteger bg1 = new BigInteger("12345678912");
BigInteger bg2 = new BigInteger("98765432189");
//1.加法
System.out.println(bg1.add(bg2));
//2.减法
System.out.println(bg1.subtract(bg2));
//3.乘法
System.out.println(bg1.multiply(bg2));
//4.除法
System.out.println(bg2.divide(bg1));
System.out.println("--------------");
//5.取除数和余数的数组
BigInteger[] bg_arry = bg2.divideAndRemainder(bg1);
for(int i=0; i< bg_arry.length; i++) {
System.out.println(bg_arry[i]);
}
}
}
输出结果:
111111111101
-86419753277
1219326313410303298368
8
--------------
8
893
分割线一下8是除数,893是余数。