Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"] Output: 9 Explanation: ((2 + 1) * 3) = 9
坑点: 不能根据string 第一位是数字位来断定是数字 (如-12)而是要看最后一位是否为数字
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int ans = 0;
stack<int> nums;
// 数字入栈 符号则 依次进行出栈两个数 左右 右操作数 左操作数 然后压回去
for(auto s: tokens){
char tmp = *(s.end()-1);
if(tmp >= '0' && tmp <= '9')
nums.push(stoi(s));
else{
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
if(s == "+") nums.push(num1 + num2);
else if(s == "-") nums.push(num1 - num2);
else if(s == "*") nums.push(num1 * num2);
else nums.push(num1 / num2);
}
}
return nums.top();
}
};