LeetCode150 Evaluate Reverse Polish Notation

Source: Internet
Author: User

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

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:

Based on the inverse Polish expression definition, set up the stack-up number

Traversing strings, encountering numbers, entering the stack, encountering operators, removing the top two elements of the stack, and then loading the results into the stack

Code:

1 classSolution {2  Public:3     intEVALRPN (vector<string>&tokens) {4stack<int>s;5          for(inti =0; i < tokens.size (); i++) {6             if(Tokens[i] = ="+"|| Tokens[i] = ="-"|| tokens[i]=="*"|| Tokens[i] = ="/") {7                 intNUM1 =s.top ();8 S.pop ();9                 intnum2 =s.top ();Ten S.pop (); One                 if(Tokens[i] = ="+") { A                     intnum = Num1 +num2; - s.push (num); -                 } the                 if(Tokens[i] = ="-") { -                     intnum = num2-NUM1; - s.push (num); -                 } +                 if(Tokens[i] = ="*") { -                     intnum = num2 *NUM1; + s.push (num); A                 } at                 if(Tokens[i] = ="/") { -                     intnum = num2/NUM1; - s.push (num); -                 } -             } -             Else { in S.push (Atoi (Tokens[i].c_str ())); -             } to         } +         intAns =s.top (); -         returnans; the     } *};

LeetCode150 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.