rainyzz's blog

Evaluate Reverse Polish Notation

###Evaluate Reverse Polish Notation https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/“, “+”] -> (4 + (13 / 5)) -> 6

这个题没什么好说的,用栈就可以了,注意一下两个数计算的时候谁前谁后就行了。

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
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<String>();
int num1 = 0;
int num2 = 0;
for(int i = 0; i < tokens.length; i++){
if (tokens[i].equals("+")){
//calcuate
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2+num1));
}else if(tokens[i].equals("-")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2-num1));
}else if(tokens[i].equals("*")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2*num1));
}else if(tokens[i].equals("/")){
num1 = Integer.parseInt(stack.pop());
num2 = Integer.parseInt(stack.pop());
stack.push(String.format("%s", num2/num1));
}else{
//push to stack
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.peek());
}