How to solve reverse polish notation

Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.

The expression is given as a list of numbers and operands. For example: [5, 3, '+'] should return 5 + 3 = 8.

For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5, since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5.

Example:

Input:  {"15", "7", "1", "1", "+", "-", "/", "3", "*", "2", "1", "1", "+", "+", "-"}
Output: 5

Approach

C++

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

int reversePolishNotation(vector<string&tokens)
{
    int res = 0;
    stack<intst;
    int n = tokens.size();
    if (n == 0)
        return res;
    for (int i = 0i < ni++)
    {
        if (tokens[i] == "+" || tokens[i] == "-" || 
tokens[i] == "*" || 
tokens[i] == "/")
        {
            int rem;
            int x = st.top();
            st.pop();
            int y = st.top();
            st.pop();
            if (tokens[i] == "+")
                rem = y + x;
            else if (tokens[i] == "-")
                rem = y - x;
            else if (tokens[i] == "*")
                rem = y * x;
            else if (tokens[i] == "/")
                rem = y / x;
            st.push(rem);
        }
        else
        {
            int x = stoi(tokens[i]);
            st.push(x);
        }
    }
    return st.top();
}
int main()
{
    vector<stringtokens = {"15""7""1""1",
                             "+""-""/""3""*",
                             "2""1""1""+""+""-"};

    cout << reversePolishNotation(tokens<< "\n";

    return 0;
}


No comments:

Post a Comment