P1957求调代码(给关注)
查看原帖
P1957求调代码(给关注)
983008
HypixelSkyblock楼主2024/4/29 14:11

P1957

测试点状态

import java.util.Scanner;
import java.util.function.BinaryOperator;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();
        scanner.nextLine(); // Consume newline

        char lastOperation = ' ';
        int lastResult = 0;

        // Define operations using a map of characters to BinaryOperator<Integer>
        Map<Character, BinaryOperator<Integer>> operations = new HashMap<>();
        operations.put('a', (x, y) -> x + y);
        operations.put('b', (x, y) -> x - y);
        operations.put('c', (x, y) -> x * y);

        for (int j = 0; j < i; j++) {
            String[] input = scanner.nextLine().split(" ");
            char operation;
            int number1, number2;

            if (input.length == 3) {
                operation = input[0].charAt(0);
                number1 = Integer.parseInt(input[1]);
                number2 = Integer.parseInt(input[2]);
            } else {
                operation = lastOperation;
                number1 = lastResult;
                number2 = Integer.parseInt(input[0]);
            }

            // Use the operation from the map
            int result = operations.getOrDefault(operation, (x, y) -> {
                throw new IllegalArgumentException("Invalid operation.");
            }).apply(number1, number2);

            String expression = number1 + (operation == 'a' ? "+" : operation == 'b' ? "-" : "*") + number2 + "=" + result;
            int length = expression.length();

            System.out.println(expression);
            System.out.println(length);

            lastOperation = operation;
            lastResult = result;
        }

        scanner.close();
    }
}

2024/4/29 14:11
加载中...