-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPostfixEvaluator.java
More file actions
49 lines (40 loc) · 1.67 KB
/
PostfixEvaluator.java
File metadata and controls
49 lines (40 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Stack;
public class PostfixEvaluator {
public static int evaluatePostfix(String expression) {
Stack<Integer> stack = new Stack<>();
// Split the expression by spaces
String[] tokens = expression.split(" ");
for (String token : tokens) {
if (isOperator(token)) {
// Pop the top two operands
int operand2 = stack.pop();
int operand1 = stack.pop();
// Apply the operator and push the result back to the stack
int result = applyOperator(token.charAt(0), operand1, operand2);
stack.push(result);
} else {
// It's a number, push it to the stack
stack.push(Integer.parseInt(token));
}
}
// The final result is at the top of the stack
return stack.pop();
}
private static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
private static int applyOperator(char operator, int operand1, int operand2) {
switch (operator) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
default: throw new IllegalArgumentException("Unknown operator: " + operator);
}
}
public static void main(String[] args) {
String expression = "1 2 + 3 *";
int result = evaluatePostfix(expression);
System.out.println("Result of the postfix expression: " + result); // Output: 9
}
}