Evaluate Reverse Polish Notation (Stack)

Source: Internet
Author: User
Tags stack pop

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

Valid operators is + , - , * , / . Each operand is an integer or another expression.

Some Examples:

  ["2", "1", "+", "3", "*")--((2 + 1) (3)-9  ["4", "", "5", "/", "+"], 4 + (13/5))

Analysis:

/*-----Reverse Polish Notation (inverse Polish expression), also known as a suffix expression . In the usual expression, the two-dollar operator is always placed between the two operands associated with it, and this notation is also known as infix notation. Polish logic J.lukasiewicz in 1929 another way of expressing expressions, in which each operator is placed after its operand, is called a suffix.

AdvantagesIts advantage is that only two simple operations, into the stack and out of the stack can be done for any ordinary expression operation. The operation is as follows: If the current character is a variable or a number, then the stack, if it is an operator, the top two elements of the stack pop up for the corresponding operation, the result is then into the stack, and finally when the expression scan, the stack is the result. -----* * Idea: Use the stack to solve the problem. Note that we also need to implement the conversion between integers and strings.
Class Solution {Public:int EVALRPN (vector<string> &tokens) {stack<int> cache;  for (int i = 0; i < tokens.size (); i++) {if (tokens[i] = = "+" | | tokens[i] = "-" | | tokens[i] = = "*" ||                  Tokens[i] = = "/") {int num2 = Cache.top ();                  Cache.pop ();                  int num1 = Cache.top ();                  Cache.pop ();              Cache.push (Calculate (NUM1, num2, Tokens[i]));              } else{Cache.push (Str2Int (tokens[i));      }} return Cache.top ();          } int Str2Int (string s) {int result=0;          int base=1;              for (int i = s.size () -1;i>=0;i--) {if (s[i] = = '-' && i = = 0) {result *=-1;                  } else if (S[i] >= ' 0 ' && s[i] <= ' 9 ') {result + = base * (s[i]-' 0 ');            Base *= 10;  }} return result;          } int Calculate (int num1, int num2, string op) {if (op = = "+") {return num1 + num2;          } else if (op = = "-") {return num1-num2;          } else if (op = = "*") {return NUM1 * NUM2;          }else if (op = = "/") {return num1/num2;  }      }  };

Other methods:

Class Solution {Public:int EVALRPN (vector<string>& tokens) {stack<int> s; for (AutoT:tokens) {//automatic type inference if (t = = "+" | | t = "-" | | t = = "*" | | t = = "/"                ) {int y = s.top (); S.pop (); int x = S.top ();                S.pop ();                int z = 0;                        Switch (T.front ()) {case ' + ': z = x + y;                    Break                        Case '-': z = x-y;                    Break                        Case ' * ': z = x * y;                    Break                        Case '/': z = x/y;                Break            } s.push (z); } else {S.push (Stoi(t)); How to spin a string using the function Std::stoi () function prototype:
                                          int stoi (const string& str, size_t* idx = 0, int base = 10); Base is a binary                                                 
            }        }        return S.top ();}    };

Use Is_operator to be more concise:

Class Solution {public:    int EVALRPN (vector<string>& tokens) {    stack<int> stn;    for (auto S:tokens) {        isdigit(s[0]) Stn.push (stoi(s));        else {            auto x2=stn.top (); Stn.pop ();            Auto X1=stn.top (); Stn.pop ();            Switch (S[0]) {break                ;                Case '-': x1-=x2; break;                Case ' * ': x1*=x2; break;                Case '/': x1/=x2; break;            }            Stn.push (x1);        }    }    return Stn.top ();}};

  

Evaluate Reverse Polish Notation (Stack)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.