-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevalRPN.java
More file actions
23 lines (23 loc) · 750 Bytes
/
evalRPN.java
File metadata and controls
23 lines (23 loc) · 750 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String c : tokens) {
if (c.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (c.equals("-")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b - a);
} else if (c.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (c.equals("/")) {
int a = stack.pop();
int b = stack.pop();
stack.push(b / a);
} else {
stack.push(Integer.parseInt(c));
}
}
return stack.pop();
}
}