2016-07-16 62 views
-5

(編輯:在更多人倒下之前,我事先看過Javadoc,但因爲我是初學者,所以我不確定在文檔中的哪個位置看到,請參閱我對Jim G的迴應,該文章在下面發佈。這個問題可能被視爲太基礎了,但我認爲它對我的情況有其他初學者有一定的價值,所以請從初學者的角度考慮全部情況)如何用整數分隔BigInteger?

我想將BigInteger除以一個正則整數(即int),但我不知道如何做到這一點。我在Google和Stack Exchange上做了一個快速搜索,但沒有找到任何答案。

那麼,我怎樣才能通過int來分割BigInteger?當我們處理它時,我如何添加/減去BigInts以進行整數,將BigInts與整數進行比較等等?

+3

請閱讀[Javadoc中'BigInteger'](https://docs.oracle.com/javase/8/docs/api/java/math/BigInteger.html) –

+1

轉換整型爲BigInteger ,然後使用採用BigInteger參數的各種方法 – yshavit

+0

感謝Jim和yshavit,將會這樣做。 –

回答

3

只需使用BigInteger.valueOf(long)工廠方法。一個int可以隱含地「擴大」爲很長的時間......當從小到大時,總是如此。 byte => short,short => int,int => long。

BigInteger bigInt = BigInteger.valueOf(12); 
int regularInt = 6; 

BigInteger result = bigInt.divide(BigInteger.valueOf(regularInt)); 

System.out.println(result); // => 2 
+0

請參閱編輯。 – Kaushal28

+0

@ Kaushal28仍然使用Integer.toString()... – Adam

+0

感謝您的回答。在此之前我並沒有意識到,整數是長整數。但Kaushal的回答也非常有幫助,因爲它讓我意識到需要查看Javadoc中的「構造函數」部分。 –

-2

轉換的IntegerBigInteger比劃分兩個BigInteger,如下:

BigInteger b = BigInteger.valueOf(10); 
int x = 6; 

//convert the integer to BigInteger. 

BigInteger converted = new BigInteger(Integer.toString(x)); 
//now you can divide, add, subtract etc. 

BigInteger result = b.divide(converted); //but this will give you Integer values. 

System.out.println(result); 

result = b.add(converted); 

System.out.println(result); 

師以上會給你區劃Integer值,得到精確值,使用BigDecimal

編輯:

要刪除兩個中間變量converted和在上面的代碼result

BigInteger b = BigInteger.valueOf(10); 
int x = 6; 

System.out.println(b.divide(new BigInteger(Integer.toString(x)))); 

OR

Scanner in = new Scanner(System.in); 
System.out.println(BigInteger.valueOf((in.nextInt())).divide(new BigInteger(Integer.toString(in.nextInt())))); 
+1

爲什麼選擇down-vote? – Kaushal28

+2

不要通過'String'從'int'轉換爲'BigInteger',使用'BigInteger.valueOf(long)' –

+2

感謝您的答案,Kaushal;但是,你能解釋一下「BigInteger轉換=新的BigInteger(Integer.toString(x))」這行嗎?「呢? –