-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_Polish_Notation.java
48 lines (38 loc) · 1.26 KB
/
Reverse_Polish_Notation.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
37
38
39
40
41
42
43
44
45
46
47
48
//Program to compute the reverse polish notation
public class Solution {
public int evalRPN(String[] tokens) {
String operators = "+-*/";
Stack<String> stack = new Stack<String>();
int returnval = 0;
if(tokens == null)
{
return -1;
}
for(String t : tokens)
{
if(!operators.contains(t))
{
stack.push(t);
}
else
{
int n1 = Integer.valueOf(stack.pop());
int n2 = Integer.valueOf(stack.pop());
int index = operators.indexOf(t);
switch(index)
{
case 0 : stack.push(String.valueOf(n1+n2));
break;
case 1: stack.push(String.valueOf(n2-n1));
break;
case 2: stack.push(String.valueOf(n1*n2));
break;
case 3: stack.push(String.valueOf(n2/n1));
break;
}
}
}
returnval = Integer.valueOf(stack.pop());
return returnval;
}
}