-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack150.java
More file actions
37 lines (35 loc) · 1.1 KB
/
Stack150.java
File metadata and controls
37 lines (35 loc) · 1.1 KB
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
package stack;
import java.util.Stack;
public class Stack150 {
public static void main(String[] args) {
String[] input = {"4", "13", "5", "/", "+"};
System.out.println(evalRPN(input));
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
int num1, num2;
for (String token: tokens) {
switch (token) {
case "+" :
stack.push(stack.pop() + stack.pop());
break;
case "-" :
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 - num2);
break;
case "*" :
stack.push(stack.pop() * stack.pop());
break;
case "/" :
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 / num2);
break;
default:
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}