Online Judge Solutions

Sunday, November 2, 2014

Evaluate Reverse Polish Notation

 
Solution 1 (in Java):

  public int evalRPN(String[] tokens) {
         Stack<Integer> stack = new Stack<Integer>();
         for(String token : tokens)
         {
             if ("+".equals(token))
                stack.push(stack.pop() + stack.pop());
             else if("-".equals(token))
                stack.push(-stack.pop() + stack.pop());
             else if("*".equals(token))
                stack.push(stack.pop() * stack.pop());
             else if("/".equals(token))
             {
                 int d1 = stack.pop();
                 int d2 = stack.pop();
                 stack.push(d2/d1);
             }
             else stack.push(Integer.parseInt(token));
         }
         return stack.pop();
    }


Solution 2 (in C++):

    bool isOperator(string &o)
    {
        return o == "+" || o == "-" || o == "*" || o == "/";
    }
   
    int atoi(const string &a)
    {
        int o = 0;
        int i = 0;
        int sign = 1;
        while(i < a.length())
        {
            if (i == 0 && a[i] == '-') {
              sign = -1;
              i++;
              continue;
            }
            o= o*10 + a[i]-'0';
            i++;
        }
       
        return o*sign;
    }
   
    int eval(int left, const string &op, int right)
    {
        int r = 0;
        if(op == "+")
               return left+ right;
        if(op == "-")
            return left - right;
        if(op == "*")
            return left * right;
         if(op == "/")
            return left / right;
            
        return 0;
    }
    int evalRPN(vector<string> &tokens) {
        stack<int> mystack;
        for(int i = 0; i < tokens.size(); i++)
        {
            if (isOperator(tokens[i]))
            {
               int right = mystack.top();
               mystack.pop();
               int left = mystack.top();
               mystack.pop();
               mystack.push(eval(left, tokens[i], right));
            }
            else
               mystack.push(atoi(tokens[i]));
        }
       
        return mystack.top();
    }

No comments:

Post a Comment