Məsələlər
Постфиксная запись
Omg, now I like Polish Notation more than traditional... ♥️
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();
}
}