题解 | 后缀表达式求值
后缀表达式求值
https://www.nowcoder.com/practice/22f9d7dd89374b6c8289e44237c70447
class Solution {
public:
/**
*
* @param tokens string字符串vector
* @return int整型
*/
int evalRPN(vector<string>& tokens) {
// write code here
stack<int> st; // 用栈存储数字
for (string& token : tokens) {
// 判断是否是运算符
if (token == "+" || token == "-" || token == "*" || token == "/") {
// 弹出两个操作数(注意顺序:先弹的是右操作数)
int num2 = st.top(); st.pop();
int num1 = st.top(); st.pop();
// 根据运算符计算
if (token == "+") st.push(num1 + num2);
if (token == "-") st.push(num1 - num2);
if (token == "*") st.push(num1 * num2);
if (token == "/") st.push(num1 / num2); // 注意整数除法规则
} else {
// 是数字:转换为int后压栈
st.push(stoi(token));
}
}
// 栈中最后一个数就是结果
return st.top();
}
};
