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
c++代码:
//Evaluate Reverse Polish Notation
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack <int> stk;
vector<string>::iterator it;
for(it=tokens.begin(); it!=tokens.end(); ++it)
{
if(isoperator(*it))
{
int a = stk.top();
// cout<<a<<*it;
stk.pop();
int b = stk.top();
// cout<<b;
stk.pop();
stk.push(operates(a,b,*it));
// cout<<"="<<stk.top()<<endl;
}
else
stk.push(atoi((*it).c_str()));
}
return stk.top();
}
bool isoperator(string st)
{
if(st=="+" || st=="-" || st=="*" || st=="/")
return true;
return false;
}
int operates(int a,int b, string op)
{
if(op=="+")
{
return a+b;
}
if(op=="-")
{
return b-a;
}
if(op=="*")
{
return a*b;
}
if(op=="/")
{
return b/a;
}
}
};
int
main(void)
{
string str[]= {"4", "3", "-"};
vector<string> strArray(str,str+(sizeof(str)/sizeof(str[0])));
Solution sn;
cout<<sn.evalRPN(strArray);
return 0;
}