Evaluate Reverse Polish Notation
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;
for(int i = 0; i != tokens.size(); i++){
if( isNum(tokens[i]))
st.push(stoi(tokens[i]));
else if(tokens[i] == "+"){
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
st.push(num1 + num2);
}else if(tokens[i] == "-"){
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
st.push(num2 - num1);
}else if(tokens[i] == "*"){
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
st.push(num1*num2);
}else if(tokens[i] == "/"){
int num1 = st.top(); st.pop();
int num2 = st.top(); st.pop();
st.push(num2/num1);
}else{
std::cout<<"Invalid token"<<std::endl;
}
}
return st.top();
}
private:
bool isNum(string &s){
int i;
for(i = 0; i != s.size() && isspace(s[i]); i++)
;
if(s[i] == '+' || s[i] == '-')
i++;
return isdigit(s[i]);
}
};