Description:
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
分析:
简单,遇到数字入栈,遇到字符,出栈两个数,再将运算结果入栈
代码:
#include <iostream>
#include <stack>
#include <vector>
#include <string>
using namespace std;
int EvaluateReversePolishNotation(vector<string> expr)
{
stack<int> sk;
string symbols = "+-*/";
for (auto it = expr.begin(); it != expr.end(); it++)
{
if (symbols.find(*it) != string::npos)
{
if (sk.size() < 2)
return INT_MIN; //表达式有误
int y = sk.top();
sk.pop();
int x = sk.top();
sk.pop();
if (*it == "+")
sk.push(x + y);
else if (*it == "-")
sk.push(x - y);
else if (*it == "*")
sk.push(x*y);
else
sk.push(x / y);
}
else
sk.push(stoi(*it));
}
return sk.top();
}
int main()
{
vector<string> expr = { "2", "1", "+", "3", "*" };
vector<string> expr2 = { "4", "13", "5", "/", "+" };
cout << EvaluateReversePolishNotation(expr) << endl;
cout << EvaluateReversePolishNotation(expr2) << endl;
system("pause");
return 0;
}
测试: