代码随想录: 代码随想录
150. 逆波兰表达式求值
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (auto c : tokens) {
if (c == "+" || c == "-" || c == "*" || c == "/") {
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
if (c == "+") {
st.push(num2 + num1);
} else if (c == "-") {
st.push(num2 - num1);
} else if (c == "*") {
st.push(num2 * num1);
} else if (c == "/") {
st.push(num2 / num1);
}
} else {
st.push(stoi(c));
}
}
int res = st.top();
st.pop();
return res;
}
};