Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
wiki explanation for RPN:
http://en.wikipedia.org/wiki/Reverse_Polish_notation
Using Stack
public class Solution {
public int evalRPN(String[] tokens) {
//by stack
//pay attention to minus and divide
Stack<String> st = new Stack<String>();
int len = tokens.length;
int res = 0;
if(len == 0) return 0;
if(len == 1) return Integer.parseInt(tokens[0]);
for(int i=0; i<len; i++){
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals ("*") || tokens[i].equals("/")){
int a = Integer.parseInt(st.pop());
int b = Integer.parseInt(st.pop());
if(tokens[i].equals ("+")){
st.push(String.valueOf(a+b));
}
else if (tokens[i].equals ("-")){
st.push(String.valueOf(b-a)); // not a-b
}
else if(tokens[i].equals ("*")){
st.push(String.valueOf(a*b));
}
else if(tokens[i].equals("/")){
st.push(String.valueOf(b/a)); // not a/b
}
}
else {
st.push(tokens[i]);
}
}
res = Integer.parseInt(st.pop());
return res;
}
}
Eg: http://www.programcreek.com/2012/12/leetcode-evaluate-reverse-polish-notation/