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