Leetcode: Evaluate reverse Polish notation

Source: Internet
Author: User

Question: Evaluate reverse Polish notation

Evaluatethe 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

A simple question, with the help of a stack, can be achieved, the value into the stack, when the operator will be two values out of the stack, after calculation re-stack, so that you can achieve.

Int evalrpn (vector <string> & tokens) {stack <int> stokens; For (INT I = 0; I <tokens. size (); ++ I) {If (tokens [I] = "+" | tokens [I] = "-" | tokens [I] = "*" | tokens [I] = "/") {int X1 = ens. top (); parameter ens. pop (); int X2 = parameter ens. top (); parameter ens. pop (); int X3 = caculate (x1, x2, tokens [I]); // re-entry stack ens after calculation. push (X3);} else {kerberens. push (atoi (tokens [I]. c_str ();} return stokens. top ();}
int caculate(int x1, int x2, string s) {    int result;    if (s == "+")        result = x1 + x2;    else if (s == "-")         result = x1 - x2;    else if (s == "*")        result = x1 * x2;    else {        if (x1 >= x2)            result = x1 / x2;        else            result = x2 / x1;    }    return result;}

 

Leetcode: Evaluate reverse Polish notation

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.