-
Notifications
You must be signed in to change notification settings - Fork 0
/
evalrpn.java
34 lines (29 loc) · 907 Bytes
/
evalrpn.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
package leetcode;
import java.util.Stack;
public class evalrpn {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for(String s : tokens) {
if(s.equals("+")) {
stack.push(stack.pop()+stack.pop());
}else if(s.equals("-")) {
stack.push(-stack.pop()+stack.pop());
}else if(s.equals("*")) {
stack.push(stack.pop()*stack.pop());
}else if(s.equals("/")) {
int nums = stack.pop();
stack.push(stack.pop()/nums);
}else {
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s = new String[] {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
evalrpn eval = new evalrpn();
int k = eval.evalRPN(s);
System.out.print(k);
}
}