Evaluate Reverse Polish Notation
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
思路:主要考察队stack的理解以及aoti()和c_str()函数的使用。
代码可以直接运行,亦可通过leetcode全部test。
#include "stdafx.h"
#include "iostream"
#include "stack"
#include "vector"
#include "string"
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens);
};
int Solution::evalRPN(vector<string>& tokens)
{
stack<int> st;
int num1, num2;
int length = tokens.size();
if (length == 1)
return atoi(tokens[0].c_str());
vector<string>::iterator iter = tokens.begin();
for (; iter != tokens.end(); iter++)
{
if (*iter == "+")
{
num2 = st.top();
st.pop();
num1 = st.top();
st.pop();
st.push(num1 + num2);
}
else if (*iter == "-")
{
num2 = st.top();
st.pop();
num1 = st.top();
st.pop();
st.push(num1 - num2);
}
else if (*iter == "*")
{
num2 = st.top();
st.pop();
num1 = st.top();
st.pop();
st.push(num1 * num2);
}
else if (*iter == "/")
{
num2 = st.top();
st.pop();
num1 = st.top();
st.pop();
st.push(num1 / num2);
}
else {
st.push(atoi((*iter).c_str()));
}
}
return st.top();
}
int main()
{
vector<string> vect;
vect.push_back("2");
vect.push_back("1");
vect.push_back("+");
vect.push_back("3");
vect.push_back("*");
Solution sol;
cout<<sol.evalRPN(vect);
system("pause");
return 0;
}
Good Luck!