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