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
题目比较简单,主要是计算逆波兰表达式的结果,逆波兰表示式的例子题目中给出来了。主要做法是遇到数字就压栈,遇到符号就计算栈顶两个元素,所以我写了一个比较长的代码,主要是为了看起来逻辑清晰一点,代码如下:
Code:(LeetCode运行9ms)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+") {
int result = s.top();
s.pop();
result += s.top();
s.pop();
s.push(result);
} else if (tokens[i] == "-") {
int result1 = s.top();
s.pop();
int result2 = s.top();
s.pop();
s.push(result2 - result1);
} else if (tokens[i] == "*") {
int result = s.top();
s.pop();
result *= s.top();
s.pop();
s.push(result);
} else if (tokens[i] == "/") {
int result1 = s.top();
s.pop();
int result2 = s.top();
s.pop();
s.push(result2 / result1);
} else {
int symbol = 1;
int sum = 0, k = pow(10, tokens[i].length() - 1);
for (int j = 0; j < tokens[i].length(); j++, k /= 10) {
if ((tokens[i])[j] == '-') {
symbol *= (-1);
} else {
sum += ((tokens[i])[j] - '0') * k;
}
}
sum *= symbol;
s.push(sum);
}
}
return s.top();
}
};