leetcode-Evaluate Reverse Polish Notation

来源:互联网 发布:陶瓷库存软件web 编辑:程序博客网 时间:2024/05/18 00:32

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 convert(string s)    {        bool isnegative = false;        int n = s.length();        int sum = 0;        int i = 0;        if(s[0] == '-')        {            isnegative = true;            i++;        }        for(; i < n; i++)        {            sum *= 10;            sum += s[i]-'0';        }        if(isnegative == false)return sum;        else return 0-sum;    }        int evalRPN(vector<string> &tokens) {        vector<int> a;        int n = tokens.size();        int m = 0;        for (int i = 0; i < n; i++)        {            int num;            if(tokens[i] == "+")            {                num = a[m-2]+a[m-1];            }            else if(tokens[i] == "-")            {                num = a[m-2]-a[m-1];            }            else if(tokens[i] == "*")            {                num = a[m-2]*a[m-1];            }            else if(tokens[i] == "/")            {                num = a[m-2]/a[m-1];            }            else            {                num = convert(tokens[i]);                a.push_back(num);                m++;                continue;            }            a.pop_back();            a.pop_back();            a.push_back(num);            m--;        }        if (m == 0)return 0;        else return a[0];    }};


0 0