题目描述
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) {
stack<int> stack;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] == "+") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(a + b);
} else if (tokens.at(i) == "-") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(b - a);
} else if (tokens.at(i) == "*") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(a * b);
} else if (tokens.at(i) == "/") {
int a = stack.top();
stack.pop();
int b = stack.top();
stack.pop();
stack.push(b / a);
} else {
//进行将string类型转换为int 类型
stack.push(stoi(tokens[i]));
}
}
return stack.top();
}
};