由后缀表达式求值

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/89474588

题目描述

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        if(tokens.size()<=0) return -1;
        stack<int>res;
        std::reverse(tokens.begin(),tokens.end());
        while(!tokens.empty())
        {
            string front=tokens.back();
            tokens.pop_back();
            if(!getoper(front)||res.empty()) res.push(atoi(front.c_str()));
            else{
                int num1=res.top();
                res.pop();
                int num2=res.top();
                res.pop();
                switch(front[0])
                {
                    case '+':res.push(num2+num1);break;
                    case '-':res.push(num2-num1);break;
                    case '*':res.push(num2*num1);break;
                    case '/':res.push(num2/num1);break;
                    default:;
                }
            }
        }
        return res.top();
    }
private:
    bool getoper(string obj)
    {
        return obj=="+"||obj=="-"
            ||obj=="*"||obj=="/";
    }
};

灵活运用字符串到数字,数字到字符的转换。

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/89474588