Evaluate Reverse Polish Notation

来源:互联网 发布:ubuntu 覆盖安装 编辑:程序博客网 时间:2024/06/05 09:29

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 compute(int op1, int op2, string &operation){if(operation.compare("+") == 0)return op1 + op2;if(operation.compare("-") == 0)return op1 - op2;if(operation.compare("*") == 0)return op1 * op2;if(operation.compare("/") == 0)return op1 / op2;}    int evalRPN(vector<string> &tokens) {stack<int> st;for(vector<string>::iterator it = tokens.begin(); it != tokens.end(); ++it){if((*it).compare("+") == 0 || (*it).compare("-") == 0 ||(*it).compare("*") == 0 ||(*it).compare("/") == 0){int op1 = st.top();st.pop();int op2 = st.top();st.pop();st.push(compute(op2, op1, *it));}elsest.push(atoi((*it).c_str()));}    return st.top();    }};


0 0
原创粉丝点击