Thursday, December 5, 2013

LeetCode Problem : Evaluate Reverse Polish Notation

Problem

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

Code

bool isOperator(const string& str)
{
    if(str.size() > 1)
    return false;
    char ch = str[0];
    switch(ch)
    {
        case '*' :
        case '/' :
        case '+' :
        case '-' :
            return true;
        default :
            return false;
    }
}
int eval(int op1,int op2,char op){
    switch(op)
    {
        case '*' :
            return (op2 * op1);
        case '/' :
            return (op2 / op1);
        case '+' :
            return (op2 + op1);
        case '-' :
            return (op2 - op1);
    }
}
int strToInt(const string& str)
{
    return atoi(str.c_str());
}

int evalRPN(vector<string> &tokens) {
    stack<int> st;
    int n = tokens.size();
    for(int i = 0;i < n; ++i){
        if(isOperator(tokens[i])){
            int op1 = st.top();
            st.pop();
            int op2 = st.top();
            st.pop();
            st.push(eval(op1,op2,tokens[i][0]));
        }
        else{
            st.push(strToInt(tokens[i]));
        }
    }
    return st.top();
}

No comments:

Post a Comment