-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPostfixCalculator.java
More file actions
33 lines (30 loc) · 1.01 KB
/
PostfixCalculator.java
File metadata and controls
33 lines (30 loc) · 1.01 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
import java.util.Stack;
class PostfixCalculator {
public static int evaluatePostfix(String expression) {
Stack<Integer> stack = new Stack<>();
String[] tokens = expression.split(" ");
for (String token : tokens) {
if (token.matches("-?\\d+")) {
stack.push(Integer.parseInt(token));
} else {
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;
case "/":
stack.push(operand1 / operand2);
break;
}
}
}
return stack.pop();
}
}