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
题目解析:
(1)因为是逆波兰式,因此遇到数字的时候就进栈,遇到符号的时候就将栈中的两个元素进行运算。
#include <iostream>
#include<vector>
#include<stack>
using namespace std;
int strTransToNum(string str)
{
int len = str.size();
int sign = 1;
int num = 0;
for(int i=0;i<len;i++)
{
if(i == 0 )
{
if(str[i] == '+')
sign = 1;
else if(str[i] == '-')
sign = -1;
else if( str[i] >= '0' && str[i] <= '9')
{
num = str[i] - '0';
}
}else{
if(str[i] >= '0' && str[i] <= '9')
{
num = num*10 + str[i]-'0';
}
}
}
return num*sign;
}
bool isOperator(string c)
{
if( !(c.compare("+")) || !(c.compare("-")) || !(c.compare("/")) || !(c.compare("*")) )
{
return true;
}else{
return false;
}
}
int evalRPN(vector<string> &tokens) {
int len = tokens.size();
if(len == 0)
return 0;
if(len == 1)
return strTransToNum(tokens[0]);
stack<int> numAndOpList;
for(int i=0;i<len;i++)
{
if(isOperator(tokens[i]))
{
int num1 = numAndOpList.top();
numAndOpList.pop();
int num2 = numAndOpList.top();
numAndOpList.pop();
if(!tokens[i].compare("+"))
numAndOpList.push(num2+num1);
if(!tokens[i].compare("-"))
numAndOpList.push(num2-num1);
if(!tokens[i].compare("*"))
numAndOpList.push(num2*num1);
if(!tokens[i].compare("/"))
numAndOpList.push(num2/num1);
}else{
numAndOpList.push(strTransToNum(tokens[i]));
}
}
int res = numAndOpList.top();
numAndOpList.pop();
if(numAndOpList.empty())
{
return res;
}else{
return 0;
}
}
int main(void)
{
vector<string> tokens;
tokens.push_back(string("0"));
tokens.push_back(string("3"));
tokens.push_back(string("/"));
cout << evalRPN(tokens) << endl;
system("pause");
return 0;
}