-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEvaluatePostfixExpression.java
More file actions
47 lines (38 loc) · 1.32 KB
/
EvaluatePostfixExpression.java
File metadata and controls
47 lines (38 loc) · 1.32 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
package datastructure.stack.program;
import datastructure.stack.Stack;
public class EvaluatePostfixExpression {
public static void main(String[] args) throws Exception {
String expression = "2 3 1 * + 9 -";
Integer result = evaluateExpression(expression);
System.out.println(result);
}
private static Integer evaluateExpression(String expression) throws Exception {
Stack<Integer> operandStack = new Stack<>();
char[] charArray = expression.toCharArray();
for (Character c : charArray) {
if (Character.isDigit(c)) {
operandStack.push(Character.getNumericValue(c));
continue;
}
if (c == ' ')
continue;
operandStack.push(calculate(c, operandStack.pop(), operandStack.pop()));
}
Integer result = operandStack.pop();
return result;
}
private static int calculate(char op, int op1, int op2) throws Exception {
switch (op) {
case '+':
return op2 + op1;
case '-':
return op2 - op1;
case '*':
return op2 * op1;
case '/':
return op2 / op1;
default:
throw new Exception("Invalid operator");
}
}
}