Leetcode: reverse words in a string: Evaluate reverse Polish notation
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
Address: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
Calculate the value of the Polish suffix expression. The specific method is to use a stack. If there is a number, the number is pushed to the stack, if an operator is encountered, the number in the stack is output to the stack for calculation (two digits in the binary operator are output to the stack, and one digit in The unary operator is output to the stack). The final result is stored in the stack. Code:
1 class Solution { 2 public: 3 int evalRPN(vector<string> &tokens) { 4 int lop, rop; 5 vector<string>::const_iterator cIter = tokens.begin(); 6 stack<int> s; 7 for(; cIter != tokens.end(); ++cIter){ 8 if ((*cIter).size() == 1 && !isdigit((*cIter)[0])){ 9 char op = (*cIter)[0];10 rop = s.top();11 s.pop();12 lop = s.top();13 s.pop();14 if (‘+‘ == op){15 s.push(lop + rop);16 } else if (‘-‘ == op){17 s.push(lop - rop);18 } else if (‘*‘ == op){19 s.push(lop * rop);20 } else{21 s.push(lop / rop);22 }23 } else {24 s.push(atoi((*cIter).c_str()));25 }26 }27 return s.top();28 }29 };