Evaluate Reverse Polish Notation LeetCode solution in C++
1class Solution {2public:3int stoi(string s) {4int n = 0;5int i = 0;6bool neg = false;7if (s[0] == '-') {8i++;9neg = true;10}11for (; i < s.size(); i++) {12n = n * 10 + (s[i] - '0');13}14if (neg) n = -n;15return n;16}17int evalRPN(vector<string> &tokens) {18stack<int> s;19int n = tokens.size();20for (int i = 0; i < n; i++) {21string str = tokens[i];22if (str == "*") {23int n1 = s.top();24s.pop();25int n2 = s.top();26s.pop();27int res = n2 * n1;28s.push(res);29} else if (str == "+") {30int n1 = s.top();31s.pop();32int n2 = s.top();33s.pop();34int res = n2 + n1;35s.push(res);36} else if (str == "/") {37int n1 = s.top();38s.pop();39int n2 = s.top();40s.pop();41int res = n2 / n1;42s.push(res);43} else if (str == "-") {44int n1 = s.top();45s.pop();46int n2 = s.top();47s.pop();48int res = n2 - n1;49s.push(res);50} else {51int num = stoi(str);52s.push(num);53}54}55return s.top();56}57};