150. Evaluation of inverse Polish expressions

Inverse Polish expression evaluation

topic

According to the reverse Polish notation, find the value of the expression.
Valid operators include +,-, *, /. Each operand can be an integer or another inverse Polish expression.

Note:
integer division only retains the integer part.
Given an inverse Polish expression is always valid. In other words, the expression always results in a valid value and there is no divisor of 0.

Example 1:

Input: [“2”, “1”, “+”, “3”, “*”]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: [“4”, “13”, “5”, “/”, “+”]
Output: 6
Explanation: (4 + (13/5)) = 6

Example 3:

Input: [“10”, “6”, “9”, “3”, “+”, “-11”, “ ", “/”, “ ”, “17”, “+”, “5”, "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

Run the code

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
 stack<int>  temp;
        for(int i=0;i<tokens.size();i++)
        {
            if(tokens[i].size()==1&&(tokens[i][0]=='+'||tokens[i][0]=='-'||tokens[i][0]=='*'||tokens[i][0]=='/'))
            {
                int temp1=temp.top();
                temp.pop();
                int temp2=temp.top();
                temp.pop();
                //cout<<"temp1:"<<temp1<<'.'<<"temp2:"<<temp2<<endl;
                if(tokens[i][0]=='+')
                    temp.push(temp1+temp2);
                else if(tokens[i][0]=='-')
                    temp.push(temp2-temp1);
                else if(tokens[i][0]=='*')
                    temp.push(temp1*temp2);
                else 
                    temp.push(temp2/temp1);
            }
            else 
            {
                temp.push(atoi(tokens[i].c_str()));
            }
            
        }
        return temp.top();
    }
};

operation result

Insert picture description here

Published 22 original articles · praised 0 · visits 295

Guess you like

Origin blog.csdn.net/qq_45950904/article/details/105033816