题目要求:
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
我的c++代码:
int evalRPN(vector<string> &tokens) { if(tokens.size() == 0) return 0; string op = "+-*/"; stack<int> st; for(size_t i = 0; i < tokens.size(); ++i) { int flag = op.find(tokens[i]); if(flag != string::npos) { if(st.size() < 2) return -1; int a = st.top(); st.pop(); int b = st.top(); st.pop(); if(flag == 0) st.push(a + b); if(flag == 1) st.push(b - a); if(flag == 2) st.push(a * b); if(flag == 3) st.push(b / a); } else st.push(atoi(tokens[i].c_str())); } return st.top(); }