Skip to content

Commit 819c083

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 150_Evaluate_Reverse_Polish_Notation.java
1 parent a08eb49 commit 819c083

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
class Solution {
2+
public int evalRPN(String[] tokens) {
3+
Stack<Integer> st = new Stack<>();
4+
5+
Set<String> operators = buildOperators();
6+
7+
for (String token : tokens) {
8+
if (!operators.contains(token)) {
9+
st.push(Integer.valueOf(token));
10+
continue;
11+
}
12+
13+
Integer num2 = st.pop();
14+
Integer num1 = st.pop();
15+
16+
int tempResult = 0;
17+
18+
switch (token) {
19+
case "+":
20+
tempResult = num1 + num2;
21+
break;
22+
case "-":
23+
tempResult = num1 - num2;
24+
break;
25+
case "*":
26+
tempResult = num1 * num2;
27+
break;
28+
case "/":
29+
tempResult = num1 / num2;
30+
break;
31+
}
32+
33+
st.push(tempResult);
34+
}
35+
36+
return st.pop();
37+
}
38+
39+
private Set<String> buildOperators() {
40+
Set<String> operators = new HashSet<>();
41+
42+
operators.add("+");
43+
operators.add("-");
44+
operators.add("*");
45+
operators.add("/");
46+
47+
return operators;
48+
}
49+
}

0 commit comments

Comments
 (0)