Skip to content

Commit 1fad162

Browse files
committed
Solution for: Evaluate reverse polish notation
1 parent 0f35818 commit 1fad162

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package leetcode;
2+
3+
import java.util.Stack;
4+
5+
public class EvaluateReversePolishNotation {
6+
7+
public static void main(String[] args) {
8+
EvaluateReversePolishNotation test= new EvaluateReversePolishNotation();
9+
System.out.println(test.evalRPN(new String[]{"2", "1", "+", "3", "*"}));
10+
System.out.println(test.evalRPN(new String[]{"4", "13", "5", "/", "+"}));
11+
12+
}
13+
14+
public int evalRPN(String[] tokens) {
15+
if(tokens.length==0) return 0;
16+
Stack<Integer> stack = new Stack<Integer>();
17+
for(int i=0; i< tokens.length; i++){
18+
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/") ){
19+
int re=0;
20+
int temp= stack.pop();
21+
if(tokens[i].equals("+")){
22+
re= stack.pop()+ temp;
23+
}
24+
if(tokens[i].equals("/")){
25+
re= stack.pop()/temp;
26+
}
27+
if(tokens[i].equals("*")){
28+
re= stack.pop()*temp;
29+
}
30+
if(tokens[i].equals("-")){
31+
re= stack.pop()- temp;
32+
}
33+
stack.push(re);
34+
}else{
35+
stack.push(Integer.parseInt(tokens[i]));
36+
}
37+
}
38+
39+
return stack.peek();
40+
}
41+
42+
}

0 commit comments

Comments
 (0)