public int evalRPN(String[] tokens) {
if (tokens==null || tokens.length == 0) return 0;
if (tokens.length == 1) return Integer.valueOf(tokens[0]);
Stack<String> stack = new Stack<String>();
String operators = "+-*/";
for (int i=0; i<tokens.length; i++) {
if (!operators.contains(tokens[i])) {
stack.push(tokens[i]);
} else {
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch(tokens[i]) {
case "+" : stack.push(String.valueOf(a+b)); break;
case "-" : stack.push(String.valueOf(b-a)); break;
case "*" : stack.push(String.valueOf(a*b)); break;
case "/" : stack.push(String.valueOf(b/a)); break;
}
}
}
return Integer.valueOf(stack.pop());
}
No comments:
Post a Comment