原题:
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
思路:逆波兰表达式,把数字推入栈中,遇到符号弹出两个处理。一开始花费了太多的时间在处理字符串上,后来直接先判断是否是运算符,再直接字符串转char(c_str()),char转int(atoi())即可。
代码:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> num;
for(int i=0; i<tokens.size(); i++){
if(tokens[i]=="*"){
int i = num.top(); num.pop();
int j = num.top(); num.pop();
num.push(i*j);
}
else if(tokens[i]=="/"){
int i = num.top(); num.pop();
int j = num.top(); num.pop();
num.push(j/i);
}
else if(tokens[i]=="+"){
int i = num.top(); num.pop();
int j = num.top(); num.pop();
num.push(i+j);
}
else if(tokens[i]=="-"){
int i = num.top(); num.pop();
int j = num.top(); num.pop();
num.push(j-i);
}
else num.push(atoi(tokens[i].c_str()));
}
return num.top();
}
};