[Leetcode] Evaluate Reverse Polish Notation

Source: Internet
Author: User

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)), 6

The problem is to evaluate the inverse Polish (suffix expression) of an arithmetic expression.

Typical application of the stack. Sequential reading of the arithmetic expression, to determine whether the read string represents an operand or an operator, if the former, then into the stack, if the latter, the top of the stack pops up two numbers, based on the currently read operators evaluated, and the results into the stack. Repeat the above steps until the expression ends.

When judging a string, you can determine whether the string is the operand by judging it to be longer than 1 or if the first character is a number.

At first, it's complicated to think that the number of operands is not just an integer, it can be a decimal, and then the situation is somewhat complicated:
1. Need to determine "operator", "decimal", "integer"
2. The types of elements in the stack need to be considered, integers and integers, decimals and decimals, integers and decimal results are different.

The following is a more comprehensive judgment on whether a string is an integer or a decimal: To determine if it is an integer, a decimal, or a real number

Put the following code:

classSolution { Public:intEVALRPN ( vector<string>&tokens) { Stack<int>OPND;intA, B; for(inti =0; I < tokens.size (); i++) {if(isalnum(tokens[i][0])|| Tokens[i].length () >1) {Opnd.push (Atoi (Tokens[i].c_str ())); }Else{a = Opnd.top ();                Opnd.pop ();                b = Opnd.top (); Opnd.pop ();Switch(tokens[i][0])                { Case ' + ': B=b+a; Break; Case '-': b=b-a; Break; Case ' * ': B=b*a; Break; Case '/': b=b/a; Break;            } opnd.push (b); }        }returnOpnd.top (); }};

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