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
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> operNumStack;
vector <string>::iterator iter;
int right;
int left;
int result;
for (iter=tokens.begin();iter<tokens.end();iter++)
{
string currentToken=*iter;
//加法
if (currentToken.compare("+")==0)
{
left=operNumStack.top();
operNumStack.pop();
right=operNumStack.top();
operNumStack.pop();
result=right+left;
operNumStack.push(result);
}
else
{
//减法
if (currentToken.compare("-")==0)
{
right=operNumStack.top();
operNumStack.pop();
left=operNumStack.top();
operNumStack.pop();
result=left-right;
operNumStack.push(result);
}
else
{
//乘法
if (currentToken.compare("*")==0)
{
right=operNumStack.top();
operNumStack.pop();
left=operNumStack.top();
operNumStack.pop();
result=right*left;
operNumStack.push(result);
}
else
{
if (currentToken.compare("/")==0)
{
right=operNumStack.top();
operNumStack.pop();
left=operNumStack.top();
operNumStack.pop();
result=left/right;
operNumStack.push(result);
}
else
{
int currentNum=atoi(currentToken.c_str());
operNumStack.push(currentNum);
}
}
}
}
}
result=operNumStack.top();
operNumStack.pop();
/*cout<<result<<endl;*/
return result;
}
};