class Solution {
public:
/*
数字入栈,然后符号入栈,将栈顶两个数字出栈,进行运算,再将结果入栈。
*/
int evalRPN(vector<string>& tokens) {
stack<int> st;
int size = tokens.size();
for (int i = 0; i < size; i++) {
// tokens 是vector!!!!
// if (isdigit(tokens[i])) {
// st.push(tokens[i]);
// }
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
if (tokens[i] == "+") {
int s2 = int(st.top());
st.pop();
int s1 = int(st.top());
st.pop();
int s = s1 + s2;
st.push(s);
}
else if (tokens[i] == "-") {
int s2 = int(st.top());
st.pop();
int s1 = int(st.top());
st.pop();
int s = s1 - s2;
st.push(s);
}
else if (tokens[i] == "*") {
int s2 = int(st.top());
st.pop();
int s1 = int(st.top());
st.pop();
int s = s1 * s2;
st.push(s);
}
else {
int s2 = int(st.top());
st.pop();
int s1 = int(st.top());
st.pop();
int s = s1 / s2;
st.push(s);
}
}
else {
// 将字符转成数字!!!!!!
st.push(stoi(tokens[i]));
}
}
int res = st.top();
return res;
}
};
总结
- 本题将字符转成数字难住了我…
- stoi()
- to_string()