Saturday, September 20, 2014

LeetCode: 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

   
   bool number(string &s)  
   {  
     char ch = s[0];  
     if(ch == '-')ch = s[1];  
     if (ch >= '0' && ch <= '9')return true;  
     return false;  
   }


int evalRPN(vector<string> &tokens) { stack<int> s; int res = 0; for (decltype(tokens.begin()) it = tokens.begin(); it != tokens.end(); it++) { if (number(*it)) { s.push(stoi(*it)); } else { string op = *it; int a = s.top(); s.pop(); int b = s.top(); s.pop(); switch(op[0]) { case '+': res = a+b; break; case '-': res = b-a; break; case '*': res = a*b; break; case '/': res = b/a; break; } s.push(res); } } return s.top(); }

No comments:

Post a Comment