From : https://leetcode.com/problems/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
class Solution {
public:
int resolve(string s) {
int num=0, size=s.size(), flag=1;
for(int i=0; i<size; i++) {
if(s[i]=='-') flag=-1;
if(s[i]>='0' && s[i]<='9') {
num = num*10 + s[i]-'0';
}
}
return flag*num;
}
int evalRPN(vector<string>& tokens) {
string cur;
stack<int> nums;
int size=tokens.size();
for(int i=0; i<size; i++) {
cur = tokens[i];
if(cur=="+" || cur=="-" || cur=="*" || cur=="/") { ////b . a
int a = nums.top();
nums.pop();
int b = nums.top();
nums.pop();
if(cur == "+") {
nums.push(b+a);
} else if(cur == "-") {
nums.push(b-a);
} else if(cur == "*") {
nums.push(b*a);
} else /*if(a!=0)*/{
nums.push(b/a);
}
} else {
nums.push(resolve(cur));
}
}
return nums.top();
}
};