Java大整形BigInteger的用法


基本類型int有32位,范圍是:[-2147483648, 2147483647](正負21億多)
基本類型long有64位,范圍是:[-9223372036854775808, 9223372036854775807]

雖然double可以表示更大的范圍,但是卻不是精確的整數。因此當需要使用到超出范圍的整數時,就需要“大整形”。Java 中的大整形類java.math.BigInteger沒有范圍限制,使用方法如下:

BigInteger的創建:

BigInteger bi1 = new BigInteger("123");
BigInteger bi2 = BigInteger.valueOf(234L);

BigInteger zero = BigInteger.ZERO;
BigInteger one = BigInteger.ONE;
BigInteger ten = BigInteger.TEN;

BigInteger的輸入輸出:

// 控制台讀入大整數
Scanner scanner = new Scanner(System.in);
BigInteger bi3 = scanner.nextBigInteger();
BigInteger bi4 = new BigInteger(scanner.nextLine());
// 控制台輸出
System.out.println(bi1);
System.out.println(bi1.toString()); // 10進制
System.out.println(bi1.toString(2)); // 2進制
// 二進制位數
int len = bi1.bitLength();

BigInteger的比較:

boolean equals = bi1.equals(bi2);
int cmp = bi1.compareTo(bi2);

BigInteger的運算:

// 加
BigInteger sum = bi1.add(bi2);
// 減
BigInteger sub = bi1.subtract(bi2);
// 乘
BigInteger mul = bi1.multiply(bi2);
// 除
BigInteger div = bi1.divide(bi2);
// 取余
BigInteger mod = bi1.remainder(bi2);
// 除數與余數 result[0]是商,result[1]是余數
BigInteger[] result = bi1.divideAndRemainder(bi2);
// 冪
BigInteger pow = bi1.pow(4);
// 相反數
BigInteger neg = bi1.negate();
// 絕對值
BigInteger abs = bi1.abs();
// 最大公約數
BigInteger gcd = bi1.gcd(bi2);

BigInteger轉換為基本類型:

byte byteValue = bi1.byteValue();
byte byteValueExact = bi1.byteValueExact();
short shortValue = bi1.shortValue();
short shortValueExact = bi1.shortValueExact();
int intValue = bi1.intValue();
int intValueExact = bi1.intValueExact();
long longValue = bi1.longValue();
long longValueExact = bi1.longValueExact();
float floatValue = bi1.floatValue();
double doubleValue = bi1.doubleValue();

其中,大整形超出相應基本類型時截斷高位,超出浮點型的范圍時為InfinityxxxValueExact()方法則是拋出ArithmeticException異常。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM