Evaluate Reverse Polish Notation

来源:互联网 发布:人工智能技术失控 编辑:程序博客网 时间:2024/06/06 20:24

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) {        stack<int> s_opd;        int lopt = 0;        int ropt = 0;        for(int i = 0; i < tokens.size(); i++) {            if(tokens[i] == "+"){                // pick out the first number                lopt = s_opd.top();                s_opd.pop();                // pick out the second number                ropt = s_opd.top();                s_opd.pop();                // push the result                s_opd.push(ropt + lopt);            } else if (tokens[i] == "-") {                lopt = s_opd.top();                s_opd.pop();                ropt = s_opd.top();                s_opd.pop();                s_opd.push(ropt - lopt);                            }else if(tokens[i] == "*") {                lopt = s_opd.top();                s_opd.pop();                ropt = s_opd.top();                s_opd.pop();                s_opd.push(ropt * lopt);                            }else if(tokens[i] == "/") {                lopt = s_opd.top();                s_opd.pop();                ropt = s_opd.top();                s_opd.pop();                if(lopt == 0) {                    s_opd.push(0);                } else {                     s_opd.push(ropt / lopt);                }            } else {                s_opd.push( atoi(tokens[i].c_str()) );            }        }        return s_opd.top();    }};

注意:
1. STL stack 的pop不会返回数值,只会消除一个数据。
2.运算符 / 要考虑分母为0的情况。

0 0
原创粉丝点击