kamacoder-solutions
kamacoder-solutions copied to clipboard
1. A+B问题I Java
最简单的解法
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum = a + b;
System.out.println(sum);
}
scanner.close();
}
}
在优化一下减少nextInt调用次数
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (scanner.hasNextLine()) {
// 一次读取一行,减少内存消耗,通过正则分割
String[] input = scanner.nextLine().split(" ");
int a = Integer.parseInt(input[0]);
int b = Integer.parseInt(input[1]);
int sum = a + b;
output.append(sum).append("\n");
}
System.out.print(output);
scanner.close();
}
}
请问方法2的好处在哪里呢?实际笔试时需要考虑这些吗?