题目内容
题目链接
java解答
class Solution {
public int evalRPN(String[] tokens) {
//申请个栈
Stack<Integer>stack=new Stack<>();
for(int i=0;i<tokens.length;i++){
//半天才发现字符串数组,一直以为是字符数组,人傻了,怪不得报了半天错.
String token = tokens[i];
int a=0;
int num1,num2;
switch (token) {
case "+":
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 + num2);
a=1;
break;
case "-":
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 - num2);
a=1;
break;
case "*":
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 * num2);
a=1;
break;
case "/":
num2 = stack.pop();
num1 = stack.pop();
stack.push(num1 / num2);
a=1;
break;
default:
}if(a==0){
//字符串转整形
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
}