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
反向波兰表示法的求解,申明一个stack,对每次出现的操作符,进行stack最顶两个元素的操作。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
int a,b;
for(int i=0;i<tokens.size();i++){
if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){
a=st.top();st.pop();
b=st.top();st.pop();
if(tokens[i]=="+")st.push(a+b);
else if(tokens[i]=="-")st.push(b-a);
else if(tokens[i]=="*")st.push(a*b);
else if(tokens[i]=="/")st.push(b/a);
}else{
st.push(stoi(tokens[i]));
}
}
if(st.empty())return 0;
else return st.top();
}
};