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
分析:
简单,遇到数字入栈,遇到字符,出栈两个数,再将运算结果入栈
代码:
测试:
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; }
测试:
相关文章推荐
- C/C++与Lua互调案例
- Lua在vs2013的配置环境以及C++如何调用lua
- 施工中 ToLua学习笔记(十一) Example 11 Delegate
- lua文件读写
- lua 字符串 正则表达式 转义 特殊字符
- mac下安装Lua
- lua中截取UTF8字符串的方法(无乱码)
- Lua 解析XML
- lua的string库
- Lua Development Tools 调试
- LeetCode之EvaluateReversePolishNotation
- Lua 基础
- Lua手动编译姿势
- 在C/C++项目中接入LuaSQLite3
- Lua版本冒泡算法及其优化
- lua math库
- lua string库
- Lua闭包的详解
- Lua 读表代码,自动生成字段名字
- lua 语法