博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-150-Evaluate Reverse Polish Notation]
阅读量:6955 次
发布时间:2019-06-27

本文共 3052 字,大约阅读时间需要 10 分钟。

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

1 int evalRPN(vector
& tokens) 2 {
//字符串可以直接比较。。不用strcmp 直接tokens[i]=="*" 3 stack
st; 4 for (int i = 0; i < tokens.size();i++) 5 { 6 if (atoi(tokens[i].c_str())!=0)st.push(atoi(tokens[i].c_str()));//返回非0代表为数字 7 else if (strcmp(tokens[i].c_str(), "0") == 0) 8 { 9 st.push(atoi(tokens[i].c_str())); 10 }11 else12 { 13 int b = st.top();14 st.pop();15 int a = st.top();16 st.pop();17 if (strcmp(tokens[i].c_str(), "+")==0) st.push(a + b); 18 else if (strcmp(tokens[i].c_str(), "-") == 0)st.push(a - b);19 else if (strcmp(tokens[i].c_str(), "*") == 0)st.push(a * b);20 else if (tokens[i] == "/")st.push(a / b);21 else22 {23 //说明有别的字符 错误 24 }25 }26 }27 return st.top();28 }

 

1  int evalRPN(vector
&tokens) { 2 stack
st; 3 int s1,s2; 4 s1=s2=0; 5 int res=0; 6 for(vector
::iterator iter=tokens.begin();iter!=tokens.end();iter++) 7 { 8 if (*iter == "+") 9 {10 s1=st.top();11 st.pop();12 s2=st.top();13 st.pop();14 res=s1+s2;15 st.push(res);16 }17 18 else if (*iter == "-")19 {20 s1=st.top();21 st.pop();22 s2=st.top();23 st.pop();24 res=s2-s1;25 st.push(res);26 }27 else if (*iter == "*")28 {29 s1=st.top();30 st.pop();31 s2=st.top();32 st.pop();33 res=s1*s2;34 st.push(res);35 }36 else if (*iter== "/")37 {38 s1=st.top();39 st.pop();40 s2=st.top();41 st.pop();42 res=s2/s1;43 st.push(res);44 }45 else 46 {47 st.push(atoi((*iter).c_str()));48 }49 }50 return st.top(); 51 53 }

 

转载于:https://www.cnblogs.com/hellowooorld/p/6432921.html

你可能感兴趣的文章
apper安卓×××
查看>>
大型网站技术架构(一)大型网站架构演化
查看>>
Log4j 1使用教程
查看>>
如何将PDF转换成Word
查看>>
svn配置
查看>>
ActiveMQ快速入门
查看>>
plusgantt的项目管理系统实战开发最全课程
查看>>
vlan理论03-vlan映射
查看>>
Linux终端的总结和shell
查看>>
在Linux下使用命令发送邮件附件
查看>>
DNS bind
查看>>
Java8 十大新特性详解
查看>>
Maven学习总结(五)——聚合与继承
查看>>
MyBatis学习总结(四)——解决字段名与实体类属性名不相同的冲突
查看>>
全局变量的使用
查看>>
Oracle AWR 阙值影响历史执行计划
查看>>
Ubuntu下mysql修改字符集为utf8
查看>>
清除浮动的七种方式方法(实例代码讲解)
查看>>
Windows Server 2012 之部署Windows Server 更新服务(1)
查看>>
搭建一个wordpress
查看>>