eolymp
bolt
Try our new interface for solving problems
Məsələlər

Постфиксная запись

dərc olunub 02.04.23 14:32:21

Omg, now I like Polish Notation more than traditional... ♥️

dərc olunub 03.04.24 02:15:59

import java.util.*;

public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String expression = scanner.nextLine(); int result = evaluatePostfix(expression); System.out.println(result); }

public static int evaluatePostfix(String expression) {
    Stack<Integer> stack = new Stack<>();
    String[] tokens = expression.split(" ");

    for (String token : tokens) {
        if (token.matches("-?\\d+")) { // If token is a number
            stack.push(Integer.parseInt(token));
        } else { // If token is an operator
            int operand2 = stack.pop();
            int operand1 = stack.pop();
            switch (token) {
                case "+":
                    stack.push(operand1 + operand2);
                    break;
                case "-":
                    stack.push(operand1 - operand2);
                    break;
                case "*":
                    stack.push(operand1 * operand2);
                    break;
            }
        }
    }
    return stack.pop();
}

}