[Question]
Evaluate the 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
Question]
Calculates the value of an expression in reverse Polish notation.
[Idea]
The inverse Polish formula is actually a binary tree traversal.
Use the stack to solve the problem. Each time an operator is encountered, it is the two elements at the top of the computing stack.
Note:
When converting a string to an integer, consider negative numbers.
[Code]
Class solution {public: int str2int (string token) {int num = 0; int start = 0; int isnev = 1; // determine the symbol if (token [0] = '-') {isnev =-1; Start ++;} else if (token [0] = '+ ') start ++; For (INT I = start; I <token. length (); I ++) {num = 10 * num + (token [I]-'0');} return num * isnev;} bool Isop (string token) {If (token = "/" | token = "+" | token = "-" | token = "*") return true ;} int evalrpn (vector <string> & tokens) {stack <int> st; For (INT I = 0; I <tokens. size (); I ++) {If (Isop (tokens [I]) {// if it is an operator, the top element of the stack is calculated, then, import the result to the stack int val1 = ST. top (); ST. pop (); int val2 = ST. top (); ST. pop (); int res = 0; If (tokens [I] = "+") RES = val2 + val1; else if (tokens [I] = "-") res = val2-val1; else if (tokens [I] = "*") RES = val2 * val1; else if (tokens [I] = "/") res = val2/val1; // calculate the result into the stack St. push (RES);} else {// number into Stack St. push (str2int (tokens [I]);} return St. top ();}};