在栈顶进行操作,没遇到符号,取出两个数,计算后放回栈中,注意两数相乘时,结果的范围可能超出int的范围
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long> stk;
for(string& s:tokens){
if(s == "+"){
int num1 = stk.top();
stk.pop();
int num2 = stk.top();
stk.pop();
stk.push(num1 + num2);
}else if(s == "-"){
int num1 = stk.top();
stk.pop();
int num2 = stk.top();
stk.pop();
stk.push(num2 - num1);
}else if(s == "*"){
long num1 = stk.top();
stk.pop();
long num2 = stk.top();
stk.pop();
stk.push(num2 * num1);
}else if(s == "/"){
int num1 = stk.top();
stk.pop();
int num2 = stk.top();
stk.pop();
stk.push(num2 / num1);
}else{
stk.push(std::stoi(s));
}
}
return stk.top();
}
};