[LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
2013-12-21 00:21 庸男勿扰 阅读(331) 评论(0) 编辑 收藏 举报原题链接:http://oj.leetcode.com/problems/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
题解:
所谓逆波兰式,即操作符位于操作数之后的表示法,我们常见的表示“三加四”都是表示成“3+4”,这是一种中缀表达式,换成逆波兰式,就应该表示成3 4 +,因此逆波兰式也称“后缀表达式”,具体的关于逆波兰式、中缀表达式、波兰式(即前缀表达式),参见维基百科。
很显然,具体操作符最近的两个数便是与这个操作符对应的操作数,用栈来实现是最直观的,这道题一道比较基础的栈的应用题,详情见代码:

1 #include <cstdio> 2 #include <cstdlib> 3 #include <string> 4 #include <vector> 5 #include <iostream> 6 #include <stack> 7 using namespace std; 8 9 int evalRPN(vector<string> &tokens) 10 { 11 vector<string>::iterator iter; 12 stack<int> res; 13 int a,b; 14 for (iter=tokens.begin();iter!=tokens.end();iter++) 15 { 16 if(*iter=="+" || *iter=="-" || *iter=="*" || *iter=="/") 17 { 18 b = res.top(); 19 res.pop(); 20 a = res.top(); 21 res.pop(); 22 if(*iter=="+") 23 { 24 res.push(a+b); 25 }else if(*iter=="-") 26 { 27 res.push(a-b); 28 }else if(*iter=="*") 29 { 30 res.push(a*b); 31 }else if(*iter=="/") 32 { 33 res.push(a/b); 34 } 35 } 36 else 37 { 38 res.push(atoi((*iter).data())); 39 } 40 } 41 return res.top(); 42 } 43 44 int main() 45 { 46 freopen("in.in","r",stdin); 47 freopen("out.out","w",stdout); 48 49 vector<string> tokens; 50 51 string t; 52 while(!cin.eof()) 53 { 54 cin>>t; 55 tokens.push_back(t); 56 } 57 58 printf("%d\n",evalRPN(tokens)); 59 return 0; 60 }
作者:庸男勿扰
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~
出处:http://www.cnblogs.com/codershell
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果您觉得对您有帮助,不要忘了推荐一下哦~
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析