今天參考課本寫了一個關於二進制與十進制轉換的程序,程序算法不難,但寫完后測試發現不論是二轉十還是十轉二,對於大於21億即超過整數范圍的數不能很好的轉換。都會變成0.
參考書籍發現使用使用BigInteger可以解決這個問題。
於是查找了下JDK,然后測試幾次終於寫成功了!
使用心得如下:
1,BigInteger屬於java.math.BigInteger,因此在每次使用前都要import 這個類。偶開始就忘記import了,於是總提示找不到提示符。
2,其構造方法有很多,但現在偶用到的有:
BigInteger(String |
BigInteger(String |
如要將int型的2轉換為BigInteger型,要寫為BigInteger two=new BigInteger("2"); //注意2雙引號不能省略
3,BigInteger類模擬了所有的int型數學操作,如add()==“+”,divide()==“-”等,但注意其內容進行數學運算時不能直接使用數學運算符進行運算,必須使用其內部方法。而且其操作數也必須為BigInteger型。
如:two.add(2)就是一種錯誤的操作,因為2沒有變為BigInteger型。
4,當要把計算結果輸出時應該使用.toString方法將其轉換為10進制的字符串,詳細說明如下:
String |
toString() 返回此 BigInteger 的十進制字符串表示形式。 |
輸出方法:System.out.print(two.toString());
5,另外說明三個個用到的函數。
BigInteger |
remainder(BigInteger |
BigInteger |
negate() 返回其值是 (-this) 的 BigInteger。 |
int |
compareTo(BigInteger |
remainder用來求余數。
negate將操作數變為相反數。
compare的詳解如下:
compareTo
public int compareTo(BigInteger val)
-
Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is:
(x.compareTo(y) <
op>
0), where <
op> is one of the six comparison operators.
-
- Specified by:
-
compareTo
in interfaceComparable<BigInteger>
-
- Parameters:
-
val
- BigInteger to which this BigInteger is to be compared. - Returns:
- -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.

import java.math.BigInteger; public class BigIntegerDemo { public static void main(String[] args) { BigInteger big=BigInteger.ONE; System.out.println("BigInteger.ONE:"+big); System.out.println("nextProbablePrime:"+big.nextProbablePrime()); System.out.println("nextProbablePrime:"+big.nextProbablePrime()); big=BigInteger.TEN; System.out.println("BigInteger.TEN:"+big); big=BigInteger.ZERO; System.out.println("BigInteger.ZERO:"+big); } }
輸出:
BigInteger.ONE:1 nextProbablePrime:2 nextProbablePrime:2 BigInteger.TEN:10 BigInteger.ZERO:0