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) { stack<int> st; int len = tokens.size(); int i = 0; int tem; while(i<len) { if(!isdigit(tokens[i][0])&&tokens[i].length()==1) { switch(tokens[i][0]) { case '+': tem = st.top(); st.pop(); tem +=st.top(); st.top() = tem; break; case '-': tem = st.top(); st.pop(); tem =st.top() - tem; st.top() = tem; break; case '*': tem = st.top(); st.pop(); tem *=st.top(); st.top() = tem; break; case '/': tem = st.top(); st.pop(); tem =st.top()/tem; st.top() = tem; break; default: break; } } else { tem = atoi(tokens[i].c_str()); st.push(tem); } i++; } return st.top(); } };
说明:
1. 字符串string str, 转化成c格式的操作:
str.c_str();
2. 字符串变整数,包括符号了, 负数也可以
atoi(str.c_str());
3.str可以当作数组操作