Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
很基础的题。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
stack<int> st;
int num1, num2;
int i, j;
for (i=0; i<tokens.size(); ++i) {
if (tokens[i]=="+" || tokens[i]=="-"
|| tokens[i]=="*" || tokens[i]=="/") {
num2 = st.top();
st.pop();
num1 = st.top();
st.pop();
st.push(cal(num1, num2, tokens[i]));
}
else {
st.push(strToInt(tokens[i]));
}
}
return st.top();
}
private:
int strToInt(const string &numStr) {
int ret = 0;
int i = 0, sign = 1;
if (numStr[i] == '-') {
sign = -1;
++i;
}
for (; i<numStr.size(); ++i) {
ret = ret*10 + (numStr[i]-'0');
}
if (sign==-1)
ret = -ret;
return ret;
}
int cal(int num1, int num2, const string &op) {
int ret = 0;
if (op == "+") {
ret = num1 + num2;
}
else if (op == "-") {
ret = num1 - num2;
}
else if (op == "*") {
ret = num1 * num2;
}
else if (op == "/") {
ret = num1 / num2;
}
return ret;
}
};
但是还要考虑给出的逆波兰表达式是否合法,要在出栈那里判断是否有两个操作数以上。还有就是如果操作数大于
int要用大整数方法。