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:
用Stack做比较好
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
public class Solution {
public int evalRPN(String[] tokens) {
List<Integer> rec = new ArrayList<>();
for(int i = 0;i<tokens.length;i++){
String tem = tokens[i];
if(tem.equals("+")){
int x=rec.size()-1;
int a=rec.get(x);
rec.remove(x);
int b=rec.get(x-1);
rec.remove(x-1);
int c=b+a;
rec.add(c);
}else if(tem.equals("-")){
int x=rec.size()-1;
int a=rec.get(x);
rec.remove(x);
int b=rec.get(x-1);
rec.remove(x-1);
int c=b-a;
rec.add(c);
}
else if(tem.equals("*")){
int x=rec.size()-1;
int a=rec.get(x);
rec.remove(x);
int b=rec.get(x-1);
rec.remove(x-1);
int c=b*a;
rec.add(c);
}
else if(tem.equals("/")){
int x=rec.size()-1;
int a=rec.get(x);
rec.remove(x);
int b=rec.get(x-1);
rec.remove(x-1);
int c=b/a;
rec.add(c);
}else{//是数字
rec.add(Integer.parseInt(tem));
}
}
return rec.get(0);
}
}