Evaluate the value of an arithmetic expression in Reverse Polish Notation
Valid operators are +,-,*,/. Each operand may be an integer or another expression.
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// notationstatic int evalRPN(String[] tokens) {Stack<Integer> st = 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 stackreturn st.pop();}}
C++
#include <bits/stdc++.h>using namespace std;//function to evaluate the reverse polish//notationint evalRPN(vector<string>& tokens){int res=0;stack<int> st;int n=tokens.size();if(n==0)return res;for(int i=0;i<n;i++){//if the current token is the operatorif(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){int rem;//pop top two elements from stackint 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 stackst.push(rem);}//push into the stackelse{int x=stoi(tokens[i]);st.push(x);}}//return the top of stackreturn st.top();}int main(){vector<string > str={"2", "1", "+", "3", "*"};cout<<evalRPN(str);return 0;}
No comments:
Post a Comment