BigInteger初識
在java的整數類型裡面,byte為8位,short為16位,int為32位,long為64位。
正因為這些數值的二進制位數已經固定,是以它們能表示的數值大小就有一定的範圍限制。
如果想表示比這些數值更大的數,怎麼辦呢?可以使用BigInteger來幫忙.
BigInteger用多少位二進制表示呢?其實,在BigInteger裡面使用int數組來存儲實作的.
為什麼java裡面要出現BigInteger類型呢?相信很多人有這個疑問,其實原因很簡單,它可以表達更大範圍的數值,遠遠比long表示的最大值還要大的多數。
在整數類型裡面,long可以表達最大值,如下所示:
public class Test
public static void main(String[] args)
{
System.out.println(Long.MAX_VALUE);
}
}
結果為:9223372036854775807
而使用BigInteger,則可以表示更大的值,如下面的例子:
public class Test
public static void main(String[] args)
{
BigInteger a= BigInteger.valueOf(9223372036854775807L);
BigInteger b= BigInteger.valueOf(9223372036854775807L);
BigInteger c=a.add(b);
System.out.println(c.toString());
}
}
結果為:18446744073709551614
下面說一下BigInteger的常用函數,這些函數在程式設計的時候會用到的。
因為BigInteger沒有重載”+”,”-“,”*”,“/”, “%”這五個運算操作符,是不能直接進行資料運算的,
需要調用它的相應方法:add,subtract,multiply,divide,remainder
BigInteger構造函數分析
BigInteger構造函數如下:
給構造函數傳入不同的參數都會轉變為BigInteger類型.具體使用可檢視相應api.
BigInteger常用函數分析
先來看看BigInteger的所有函數:
- 比較函數:
int compareTo(BigInteger val)
//比較大小
BigInteger min(BigInteger val)
//傳回較小的
BigInteger max(BigInteger val)
//傳回較大的
BigInteger經常遇到的問題
本文給大家說一下BigInteger的常見問題,總共有幾個常見的問題,如下所示。
問題一:在java怎樣将BigInteger類型的資料轉成int類型的?
答案:BigInteger的intValue()可以獲得int類型數值。
/**
* Converts this BigInteger to an {@code int}. This
* conversion is analogous to a
* <i>narrowing primitive conversion</i> from {@code long} to
* {@code int} as defined in section 5.1.3 of
* <cite>The Java™ Language Specification</cite>:
* if this BigInteger is too big to fit in an
* {@code int}, only the low-order 32 bits are returned.
* Note that this conversion can lose information about the
* overall magnitude of the BigInteger value as well as return a
* result with the opposite sign.
*
* @return this BigInteger converted to an {@code int}.
* @see
public int intValue() {
int result = 0;
result = getInt(0);
return
問題二:在哪裡可以檢視BigInteger的代碼實作?
答案:在jdk裡面的java.math包下面就可以看到
問題三:在JAVA中BigInteger.ZERO是什麼意思?
答案:在BigInteger内部定義的 一個代表 數字零 的常量,如下所示:
public static final BigInteger ZERO = new BigInteger(new int[0], 0);