java.math.BigInteger使用心得總結(轉)


今天參考課本寫了一個關於二進制與十進制轉換的程序,程序算法不難,但寫完后測試發現不論是二轉十還是十轉二,對於大於21億即超過整數范圍的數不能很好的轉換。都會變成0.
參考書籍發現使用使用BigInteger可以解決這個問題。
於是查找了下JDK,然后測試幾次終於寫成功了!
使用心得如下:

1,BigInteger屬於java.math.BigInteger,因此在每次使用前都要import 這個類。偶開始就忘記import了,於是總提示找不到提示符。

2,其構造方法有很多,但現在偶用到的有:

BigInteger(String val)
           將 BigInteger 的十進制字符串表示形式轉換為 BigInteger。
BigInteger(String val, int radix)
           將指定基數的 BigInteger 的字符串表示形式轉換為 BigInteger。

如要將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 val)
           返回其值為 (this % val) 的 BigInteger。
BigInteger negate()
           返回其值是 (-this) 的 BigInteger。
int        compareTo(BigInteger val)
           將此 BigInteger 與指定的 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 interface Comparable<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);
    }

}
View Code

輸出:

BigInteger.ONE:1
nextProbablePrime:2
nextProbablePrime:2
BigInteger.TEN:10
BigInteger.ZERO:0

 


免責聲明!

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



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