forked from davidals/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluatePostFix.java
More file actions
31 lines (27 loc) · 813 Bytes
/
evaluatePostFix.java
File metadata and controls
31 lines (27 loc) · 813 Bytes
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
public int evaluatePostFix(String expr) throws Exception{
if(expr == null || expr.isEmpty())
throw new Exception("Null or empty parameter");
Stack operands = new Stack();
for(int i = 0; i < expr.length(); i++){
Character c = expr.charAt(i);
if(isOperand(c))
operands.push(Integer.parseInt(c.toString()));
else{
if(operands.size() < 2)
throw new Exception("Invalid expression");
Integer op2 = operands.pop();
Integer op1 = operands.pop();
if(c.equals('+'))
operands.push(op1 + op2);
else if(c.equals('-'))
operands.push(op1 - op2);
else if(c.equals('*'))
operands.push(op1 * op2);
else if(c.equals('/'))
operands.push(op1 / op2);
else
throw new Exception("Invalid expression");
}
}
return operands.pop();
}