4/13/2014

Leetcode -- Evaluate Reverse Polish Notation

class Solution {  
 public:  
   int evalRPN(vector<string> &tokens) {  
     stack<int> stack;  
     int n = tokens.size();  
     for(int i = 0; i < n; ++i) {  
       int toPush = 0;  
       if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {  
         int right = stack.top();  
         stack.pop();  
         int left = stack.top();  
         stack.pop();  
         switch(tokens[i][0]) {  
         case '+':  
           toPush = right + left;  
           break;  
         case '-':  
           toPush = left - right;  
           break;  
         case '*':  
           toPush = left * right;  
           break;  
         case '/':  
           toPush = left / right;  
           break;  
          }  
       } else {  
         toPush = atoi(tokens[i].c_str());  
       }  
       stack.push(toPush);  
     }  
     return stack.top();  
   }  
 };  

No comments: