Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
计算逆波兰式的值,计算符号只有加减乘除,一看就是需要用到栈模拟,遇到算术符号,就从顶部取数据进行计算,再压入结果。主要注意输入是字符串,需要变成对应数字,一个技巧就是读入到输入输出流中,如下str2num,num2str,十分方便。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
return (int) solve(tokens);
}
long str2num(string s)
{
long num;
stringstream ss(s);
ss>>num;
return num;
}
string num2str(long i)
{
stringstream ss;
ss<<i;
return ss.str();
}
long solve(vector<string> & tokens)
{
stack<string> s;
for(vector<string>::iterator it = tokens.begin();it!=tokens.end();it++)
{
if (*it=="+" || *it=="-" || *it =="*" || *it=="/")
{
long op1,op2,op3;
op2 = str2num(s.top());
s.pop();
op1 = str2num(s.top());
s.pop();
if (*it=="+")
op3 = op1 + op2;
else
if(*it=="-")
op3 = op1 - op2;
else
if(*it=="*")
op3 = op1 * op2;
else
op3 = op1 / op2;
string str=num2str(op3);
s.push(str);
}
else{
s.push(*it);
}
}
return str2num(s.top());
}
};