题目:
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 evalRPN(vector<string>& tokens) {
int size=tokens.size();
stack<int> opds;
for(int i=0;i<size;++i){
if(tokens[i]=="+"){
int a=opds.top();
opds.pop();
int b=opds.top();
opds.pop();
opds.push(b+a);
}else if(tokens[i]=="-"){
int a=opds.top();
opds.pop();
int b=opds.top();
opds.pop();
opds.push(b-a);
}else if(tokens[i]=="*"){
int a=opds.top();
opds.pop();
int b=opds.top();
opds.pop();
opds.push(b*a);
}else if(tokens[i]=="/"){
int a=opds.top();
opds.pop();
int b=opds.top();
opds.pop();
opds.push(b/a);
}else {
int a=atoi(tokens[i].c_str());
opds.push(a);
}
}
return opds.top();
}
};