java中long型为最大整数类型,对于超过long型的数据如何去表示呢.在Java的世界中,超过long型的整数已经不能被称为整数了,它们被封装成BigInteger对象.在BigInteger类中,实现四则运算都是方法来实现,并不是采用运算符.
BigInteger类的构造方法:
BigInteger b = new BigInteger(str); //构造方法中,采用字符串的形式给出整数
BigInteger big1 = new BigInteger("12345678909876543210");
BigInteger big2 = new BigInteger("98765432101234567890");
//add实现加法运算
BigInteger bigAdd = big1.add(big2);
//subtract实现减法运算
BigInteger bigSub = big1.subtract(big2);
//multiply实现乘法运算
BigInteger bigMul = big1.multiply(big2);
//divide实现除法运算
BigInteger bigDiv = big2.divide(big1);
System.out.println(bigAdd);
System.out.println(bigSub);
System.out.println(bigMul);
System.out.println(bigDiv);
/**
* 111111111011111111100
* -86419753191358024680
* 1219326312117055326552354825111263526900
* 8
*/
/**
构造一个十进制的BigInteger对象,
该构造方法可以发生NumberFormatException异常,
也就是说,字符串参数VAL中如果含有非数字字符就会发生NumberFormatException异常。
*/
public BigInteger(String VAL)
BigInteger类的常用方法:
public BigInteger add(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的和
public BigInteger subtract(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的差
public BigInteger multiply(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的积
public BigInteger devide(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的商
public BigInteger remainder(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的余
public int compareTo(BigInteger val) 返回当前大整数对象与参数指定的大整数对象的比较结果,返回值是1、-1、0,分别表示当前大整数对象大于、小于或等于参数指定的大整数。
public BigInteger abs() 返回当前大整数对象的绝对值
public BigInteger pow(int exponent) 返回当前大整数对象的exponent次幂。
public String toString() 返回当前当前大整数对象十进制的字符串表示。
public String toString(int p) 返回当前大整数对象p进制的字符串表示。