在寫程式時,最怕碰到數字超過現有型態的大小,且又要做運算....
Java提供了一個BigInteger物件解除大數的煩腦
1 | import java.math.BigInteger; |
2 | public class test |
3 | { |
4 | public static void main(String [] argv) |
5 | { |
6 | String a = "1001" ; |
7 | String b = "100" ; |
8 |
9 | //建立BigInteger物件 |
10 | BigInteger big_a = new BigInteger(a); |
11 | BigInteger big_b = new BigInteger(b); |
12 |
13 | //加法使用add() |
14 | System.out.println( "a + b =" + big_a.add(big_b)); |
15 |
16 | //使用減法是將大數加上負號再產生一個BigInteger物件 |
17 | System.out.println( "a - b =" + big_a.add( new BigInteger( "-" +b))); |
18 |
19 | //乘法使用multiply() |
20 | System.out.println( "a * b =" + big_a.multiply(big_b)); |
21 |
22 | //除法使用divide() |
23 | System.out.println( "a / b =" + big_a.divide(big_b)); |
24 | |
25 | //取餘數使用mod() |
26 | System.out.println( "a mod b =" + big_a.mod(big_b)); |
27 |
28 | } |
29 | } |