evaluate-reverse-polish-notation
题目:
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
解一:

import java.util.Stack;
public class Solution {
private final static String ADD = "+";
private final static String SUBTRACT = "-";
private final static String MULTIPLY = "*";
private final static String DIVIDE = "/";
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
int op1,op2, result=0;
if(tokens.length<3){
return Integer.parseInt(tokens[0]);
}
for(int i = 0; i<tokens.length; i++){
if (isOperator(tokens[i])){
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(tokens[i],op1,op2);
stack.push(new Integer(result));
}else {
stack.push(new Integer(Integer.parseInt(tokens[i])));
}
}
return result;
}
private boolean isOperator(String token){
return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
}
private int evaluateSingleOperator(String operator, int op1 , int op2){
int result = 0;
switch (operator){
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1- op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
break;
}
return result;
}
}

浙公网安备 33010602011771号