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.

Example:

Input:  str[]={"2","1","+","3","*"}
Output: 9

Approach

Java


import java.util.Stack;

public class EvaluateReversePolishNotation {
    public static void main(String[] args) {
        String[] str = { "2""1""+""3""*" };
        System.out.println(evalRPN(str));
    }

    // function to evaluate the reverse polish
    // notation
    static int evalRPN(String[] tokens) {
        Stack<Integerst = new Stack<>();
        for (String token : tokens) {
            if (token.equals("+")) {
                st.push(st.pop() + st.pop());
            } else if (token.equals("-")) {
                int second = st.pop();
                int first = st.pop();
                st.push(first - second);
            } else if (token.equals("*")) {
                st.push(st.pop() * st.pop());
            } else if (token.equals("/")) {
                int second = st.pop();
                int first = st.pop();
                st.push(first / second);
            } else {
                st.push(Integer.parseInt(token));
            }
        }
        // return the top of stack
        return st.pop();
    }
}

C++

#include <bits/stdc++.h>
using namespace std;


//function to evaluate the reverse polish
//notation 
int evalRPN(vector<string>& tokens
{
        int res=0;
        stack<intst;
        int n=tokens.size();
        if(n==0)
              return res;
        for(int i=0;i<n;i++)
        {
            //if the current token is the operator
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
            {
                int rem;
                //pop top two elements from stack
                int x=st.top();
                st.pop();
                int y=st.top();
                st.pop();

                //if + 
                if(tokens[i]=="+")
                      rem=y+x;

                //if -
                else if(tokens[i]=="-")
                       rem=y-x;

                //if *
                else if(tokens[i]=="*")
                       rem=y*x;

                //if /
                else if(tokens[i]=="/")
                       rem=y/x;
                 //push into the stack
                st.push(rem);
                       
            }

            //push into the stack
            else
            {
                
                int x=stoi(tokens[i]);
                st.push(x);
            }
        }
     //return the top of stack
    return st.top();
}
int main()
   vector<string > str={"2""1""+""3""*"};
   cout<<evalRPN(str);
   return 0;
}



No comments:

Post a Comment