kamacoder-solutions icon indicating copy to clipboard operation
kamacoder-solutions copied to clipboard

1. A+B问题I Java

Open SerMs opened this issue 1 year ago • 1 comments

最简单的解法

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();
    }
}

SerMs avatar Oct 18 '23 07:10 SerMs

请问方法2的好处在哪里呢?实际笔试时需要考虑这些吗?

chaofengdev avatar Aug 14 '24 15:08 chaofengdev