-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluatePostfix.java
More file actions
31 lines (31 loc) · 847 Bytes
/
EvaluatePostfix.java
File metadata and controls
31 lines (31 loc) · 847 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
import java.util.Stack;
public class EvaluatePostfix{
public static void main(String[] args) {
System.out.println(eval("5, 4, 6, +, *, 4, 9, 3, /, +, *"));
}
static int eval(String expression){
Stack<Integer> s = new Stack<>();
for (int i=0;i<expression.length();i++) {
char tempValue = expression.charAt(i);
if (tempValue ==',' || tempValue == ' ')
continue;
else if (tempValue >= '0' && tempValue <= '9') {
s.push(tempValue-48);
}
else {
int temp = s.pop();
s.push(opration(s.pop(), temp, tempValue));
}
}
return s.pop();
}
static int opration(int a, int b, char oprator){
if (oprator == '+') return a+b;
if (oprator == '-') return a-b;
if (oprator == '*') return a*b;
if (oprator == '/') return a/b;
if (oprator == '^' || oprator == '$')
return (int)Math.pow(a,b);
return 0;
}
}