-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvalRPN.java
More file actions
49 lines (45 loc) · 1.39 KB
/
Copy pathEvalRPN.java
File metadata and controls
49 lines (45 loc) · 1.39 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
38
39
40
41
42
43
44
45
46
47
48
49
package stack_queue;
import org.junit.Test;
import java.util.Stack;
/**
* @Author: wei1
* @Date: Create in 2018/12/2 16:55
* @Description: 1.这种逆波兰表达式,很明显,用栈求解。
* Evaluate the value of an arithmetic expression in Reverse Polish Notation.
* <p>
* Valid operators are+,-,*,/. Each operand may be an integer or another expression.
* <p>
* Some examples:
* <p>
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
public class EvalRPN {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack();
for (int t = 0; t < tokens.length; t++) {
try {
int i = Integer.parseInt(tokens[t]);
stack.push(i);
} catch (Exception e) {
int b = stack.pop();
int a = stack.pop();
if (tokens[t].equals("+")) {
stack.add(a + b);
} else if (tokens[t].equals("-")) {
stack.add(a - b);
} else if (tokens[t].equals("*")) {
stack.add(a * b);
} else {
stack.add(a / b);
}
}
}
return stack.peek();
}
@Test
public void test() {
String[] strs = {"2", "1", "+", "3", "*"};
System.out.println(evalRPN(strs));
}
}