Java大数应用

1.大数加法

 1 import java.math.BigInteger;
 2 import java.util.Scanner;
 3 
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7         Scanner cin = new Scanner(System.in);//大数的输入,定义一个输入器
 8         BigInteger a = null, b = null, c = null;//开始要赋值成空
 9         a = BigInteger.valueOf(100);
10         b = BigInteger.valueOf(99);
11         int T;
12         T = cin.nextInt();//读入T;
13 //        while(cin.hasNextBigInteger())//判断是否读到文件结尾相当于while(~scanf())
14         for(int cas = 1; cas <= T; cas++)
15         {
16             a = cin.nextBigInteger();
17             b = cin.nextBigInteger();
18             
19 //            BigInteger zero = BigInteger.valueOf(0);//大数判断是不是等于0
20 //            if(a.equals(BigInteger.valueOf(0))){System.out.println("haha");}
21 //            if(a.equals(zero)) {System.out.println("hehe");}
22             c = a.add(b);
23             if(cas > 1) System.out.println();//大数的换行输出
24             System.out.println("Case " + cas + ":");//大数的输出是用+号连接
25             System.out.println(a + " + " + b + " = "+c);
26         }
27         cin.close();//关闭读入器
28     }
29 
30 }

2.大实数

 1 import java.math.BigDecimal;
 2 import java.util.Scanner;
 3 
 4 
 5 public class Main {
 6     public static void main(String[] args) {
 7     Scanner s = new Scanner(System.in);
 8     while(s.hasNext()){
 9         BigDecimal b = s.nextBigDecimal();
10         BigDecimal ans = BigDecimal.valueOf(1);
11         int n = s.nextInt();
12         while(n-- > 0)
13             ans = ans.multiply(b);
14         String string = ans.stripTrailingZeros().toPlainString().toString();
15         if(string.startsWith("0."))
16             string = string.substring(1);
17         System.out.println(string);
18     }
19         s.close();
20     }
21 }