您的位置:首页 > 编程语言 > Lua

Evaluate Reverse Polish Notation

2016-07-27 16:58 405 查看
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;
}


测试:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: