-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReversePolish.java
36 lines (36 loc) · 1.05 KB
/
ReversePolish.java
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
public class ReversePolish {
public int evalRPN(String[] tokens) {
int n = tokens.length;
Stack<Integer> vals = new Stack<Integer>();
int a =0;
int b=0;
for(int i=0;i<n;i++){
String symbol = tokens[i];
switch(symbol){
case "+":
a = vals.pop();
b = vals.pop();
vals.push(b+a);
break;
case "-":
a = vals.pop();
b = vals.pop();
vals.push(b-a);
break;
case "*":
a = vals.pop();
b = vals.pop();
vals.push(b*a);
break;
case "/":
a = vals.pop();
b = vals.pop();
vals.push(b/a);
break;
default:
vals.push(Integer.valueOf(tokens[i]));
}
}
return vals.pop();
}
}