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
The key to this problem is to use a stack to store those operands. Once we come with a operator, we use the first two operands on the stack to get a result and put it back to the stack. When there is only one number in the stack, it would be the result. We also have to remember to check whether a token is a number or not.
public class Solution {
public int evalRPN(String[] tokens) {
// test whether tokens are empty
if(tokens.length == 0)
{
System.out.println("No input");
return -1;
}
// use stack to collect operands
Stack<Integer> collector = new Stack<Integer>();
int l = tokens.length;
for(int i = 0; i < l; i++)
{
if ((tokens[i].equals("+")) || (tokens[i].equals("-")) || (tokens[i].equals("*")) || (tokens[i].equals("/")))
{
String str = tokens[i];
int operand2 = collector.pop();
int operand1 = collector.pop();
if(str.equals("+"))
{
collector.push(operand1 + operand2);
}
if(str.equals("-"))
{
collector.push(operand1 - operand2);
}
if(str.equals("*"))
{
collector.push(operand1 * operand2);
}
if(str.equals("/"))
{
collector.push(operand1 / operand2);
}
}
else
{
// we have to test whether this token is a integer or not
boolean flag = false;
int num = 0;
try
{
num = Integer.parseInt(tokens[i]);
}
catch(Exception e)
{
flag = true;
}
if(flag)
{
continue;
}
else
{
collector.push(num);
}
}
}
// output
if(collector.size() == 1)
{
return collector.pop();
}
return -1;
}
}