在運算的過程中所產生的值有可能超出 int
所能表示的範圍,所以 st
得用 long
或更大的 built-in type 來容納運算的過程中所產生的值。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
int op1, op2;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+") {
getOperands(st, op1, op2);
st.push(op1 + op2);
} else if (tokens[i] == "-") {
getOperands(st, op1, op2);
st.push(op1 - op2);
} else if (tokens[i] == "*") {
getOperands(st, op1, op2);
st.push(op1 *op2);
} else if (tokens[i] == "/") {
getOperands(st, op1, op2);
st.push(op1 / op2);
} else {
st.push(static_cast<int>(strtol(tokens[i].c_str(), NULL, 10)));
}
}
return st.top();
}
private:
void getOperands(stack<int> &st, int &op1, int &op2) {
op2 = st.top();
st.pop();
op1 = st.top();
st.pop();
return;
}
};
tokens
.
tokens
.
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up