题目

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

原题地址

解题思路

计算逆波兰表达式。了解很多其它关于逆波兰表达式请点击

计算逆波兰表达式这是个非常典型的栈应用的样例。

解题方法就是用栈来处理。须要注意的是本题输入给的是字符串数组,所以须要在字符串和整数之间有个转换。

代码例如以下

class Solution {
public:
int evalRPN(vector<string> &tokens) {
int ret=0;
int n = tokens.size();
if(n<=0) return ret;
stack<int> s;
int i=0;
while(i<n){
string temp = tokens[i];
int num = atoi(temp.c_str());
//防止非法输入
if(num!=0 || (num==0 && temp[0]=='0')){
s.push(num);
}else{
ret = cal(s, tokens[i][0]);
if(ret == -1) return 0;
}
++i;
}
if(!s.empty()) return s.top();
else return 0;
}
int cal(stack<int> &s, char oper){
if(s.size()<2) return -1;
int op1 = s.top(); s.pop();
int op2 = s.top(); s.pop();
if(oper == '+'){
s.push(op1+op2);
}else if(oper == '-'){
s.push(op2-op1);
}else if(oper == '*'){
s.push(op2 * op1);
}else if(oper == '/'){
if(op1 == 0) return -1;
s.push(op2 / op1);
}else return -1;
return 0;
}
};

假设你认为本篇对你有收获。请帮顶。

另外。我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.

你能够搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28243489
)

最新文章

  1. 第四篇.Bootstrap网格系统偏移列和嵌套列
  2. html给div加超链接的方法
  3. 简单使用AutoMapper实现DTO转换
  4. mock.js-无需等待,让前端独立于后端进行开发
  5. Linux网络参数设置
  6. JBoss和Tomcat版本、及Servlet、JSP规范版本对应一览 【转】
  7. [原]Unity3D深入浅出 - 认识开发环境中的RenderSettings面板
  8. python----设置默认编码
  9. 【转】经典!python中使用xlrd、xlwt操作excel表格详解
  10. AngularJS -- 指令(创建自定义指令)
  11. bootstrap---treeview使用方法
  12. Add AI feature to Xamarin.Forms app
  13. 在被vue组件引用的 js 文件里获取组件实例this
  14. [ML]机器学习书单
  15. 微信app支付的坑
  16. 《我的嵌入式开发》---- IIC 通信
  17. springmvc webservlet 异步请求总结
  18. CentOS docker 常用命令
  19. sqlserver2008 传入的表格格式数据流(tds)协议流不正确。
  20. BZOJ4858 : [Jsoi2016]炸弹攻击 2

热门文章

  1. EF中的DbContext类
  2. centos7.5安装公版mysql5.7.25
  3. 廖雪峰Java11多线程编程-1线程的概念-2创建新线程
  4. HZOI20190902模拟35题解
  5. HZOI20190810 T1
  6. Office2010 破解(Microsoft Toolkit 2.4.3.exe)
  7. dubbo入门学习(三)-----dubbo整合springboot
  8. Golang Learn Log #0
  9. 转:LPC2214的PLL与定时器设置
  10. Java内功修炼系列一观察者模式