Java大数相加-hdu1047

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1047

题目描述:

  题意有点绕,但是仔细的读了后就发现是处理大数相加的问题。注意:输入数据有多组,每组输入要用一个t来控制输入的模块,每个模块的输入以0来结束。换句话说,有多少模块,输出就有多少个VeryLongInteger。

代码实现:

 1 import java.math.BigInteger;
 2 import java.util.Scanner;
 3 
 4 public class Hdu1047 {
 5     public static void main(String[] args) {
 6         Scanner scanner = new Scanner(System.in);
 7         while (scanner.hasNext()) {
 8             int t = scanner.nextInt();//用t来控制输入多少模块
 9             while(t>0) {
10                 t--;
11                 BigInteger sum= BigInteger.ZERO;
12                 while (true) {
13                     BigInteger num = scanner.nextBigInteger();
14                     if (num .compareTo(BigInteger.ZERO)==0)//此处要用compareTo()来判断大数num是否等于0,不可直接用”==“进行比较。
15                         break;
16                     sum = sum.add(num);//大数相加要运用add(),不能直接用“+”来对大数进行相加
17                 }
18                 System.out.println(sum);
19                 if(t>0)//每个案列后有一个空行
20                     System.out.println();
21             }    
22         }
23         scanner.close();
24     }
25 }

 

posted @ 2018-12-12 20:31  里昂静  阅读(283)  评论(0编辑  收藏  举报