-
Notifications
You must be signed in to change notification settings - Fork 7
/
Main.java
34 lines (30 loc) · 997 Bytes
/
Main.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 com.company;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String[] token = {"2","1","+","3","*"};
System.out.println(evalRPN(token));
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String t : tokens) {
if (t.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (t.equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (t.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (t.equals("/")) {
int temp = stack.pop();
stack.push(stack.pop() / temp);
} else
stack.push(Integer.parseInt(t));
}
int res = 0;
while (!stack.isEmpty())
res += stack.pop();
return res;
}
}