算法设计与应用基础系列12

来源:互联网 发布:网络交友英语作文题目 编辑:程序博客网 时间:2024/06/05 11:09

Evaluate Reverse Polish Notation


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
这是一个很简单的题目,解答如下 用多个if即可解决

Algorithm:

  1. pop string from the end of the vector

  2. if it's number, just return it

  3. if it's operation, call function recursively for 2nd operand and 1st

    int evalRPN(vector<string> &n) {
    string s = n.back(); n.pop_back();
    if ( s== "" || s=="/" || s=="+" || s == "-" ){
    int r2 = evalRPN(n);
    int r1 = evalRPN(n);
    if ( s=="
    ") return r1*r2;
    if ( s=="/") return r1/r2;
    if ( s=="+") return r1+r2;
    if ( s=="-") return r1-r2;
    }
    else
    return atoi(s.c_str());
    }

原创粉丝点击