# LeetCode 150. Evaluate Reverse Polish Notation

Problem:

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```

Solution:

```public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> nums = new Stack<>();
Stack<String> ops = new Stack<>();
for (String token: tokens) {
if (isOp(token)) {
if (nums.isEmpty()) {
ops.push(token);
}
else {
String num1 = nums.pop();
String num2 = nums.pop();
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
if (token.equals("+")) {
nums.push(a + b + "");
}
else if (token.equals("-")) {
nums.push(b - a + "");
}
else if (token.equals("*")) {
nums.push(b * a + "");
}
else {
nums.push(b / a + "");
}
}
}
else {
nums.push(token);
}
}
String last = nums.pop();
return Integer.parseInt(last);
}

private boolean isOp(String s) {
String ops = "+-*/";
return ops.indexOf(s) > -1;
}
}
```

## 5 thoughts on “LeetCode 150. Evaluate Reverse Polish Notation”

1. 南明美肌蛻變魔幻日 – 南明美容集團Asia Pacific Beauty Group Limited 南明美肌蛻變魔幻日 – 南明美容集團Asia Pacific Beauty Group Limited

2. Hi my loved one! I want to say that this post is awesome, nice written and come with approximately all vital infos. I would like to see more posts like this .

3. 妝前底霜，形成柔滑亮澤薄紗，締造柔滑細緻膚質，隱藏瑕疵。

4. 無論您是首次置業、換樓或是物業投資者，富邦樓宇按揭服務，為您提供多元化按揭計劃，全面配合不同的財務需要；加上專業按揭顧問的一站式服務，助您抓緊每個 …