2016-07-16 27 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))”这行吗?“呢? –