题目描述
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
思路:
1.要记录操作两个操作数。在遍历的时候分别判断是+,-,*,/
2.分别进行运算。最后返回栈顶元素。
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack();
//操作数
int a,b;
for(int i=0;i<tokens.length;i++){
String temp=tokens[i];
switch(temp){
case "+":
a=stack.pop();
b=stack.pop();
stack.push(b+a);
break;
case "-":
a=stack.pop();
b=stack.pop();
stack.push(b-a);
break;
case "*":
a=stack.pop();
b=stack.pop();
stack.push(b*a);
break;
case "/":
a=stack.pop();
b=stack.pop();
if(a==0){
return -1;
}
stack.push(b/a);
break;
default:
stack.push(Integer.parseInt(temp));
}
}
return stack.peek();
}
}