7-2-Java-基本语法-大整数相加

题目

有若干大整数,需要对其进行求和操作。

输入格式

每行输入一个字符串代表一个大整数,连续输入若干行,当某行字符为e或E时退出。

输入样例:

1
2
3
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
e

输出样例:

1
97967883730498271109594004638709798272918548148116

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})

let sum = BigInt(0)

rl.on('line', line => {
if (!line.localeCompare("e", undefined, { sensitivity: "base" })) {
console.log(sum.toString())
rl.close()
} else {
sum += BigInt(line)
}
})

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.Scanner;
import java.math.BigInteger;

public class Main {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
BigInteger sum = BigInteger.ZERO;

while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.equalsIgnoreCase("e")) {
System.out.println(sum.toString());
break;
} else {
sum = sum.add(new BigInteger(line));
}
}
scanner.close();
}
}