150. 逆波兰表达式求值
栈
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> ans;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == "+"){
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(a + b);
}
else if(tokens[i] == "-"){
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(b - a);
}
else if(tokens[i] == "*"){
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(a * b);
}
else if(tokens[i] == "/"){
int a = ans.top();
ans.pop();
int b = ans.top();
ans.pop();
ans.push(b / a);
}
else{
string str = tokens[i];
int cnt = 0;
if(str[0] == '-'){
for(int j = 1; j < str.length(); j++){
cnt = cnt*10 + (str[j] - '0');
}
cnt = -cnt;
}
else{
for(int j = 0; j < str.length(); j++){
cnt = cnt*10 + (str[j] - '0');
}
}
ans.push(cnt);
}
}
return ans.top();
}
};