当前位置:网站首页>逆波兰表达式求值
逆波兰表达式求值
2022-08-03 22:55:00 【老鱼37】

思路:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
//创建一个栈
stack<int>v;
for(string &ch:tokens)
{
if(ch=="+"||ch=="-"||ch=="/"||ch=="*")
{
//弹出栈中两个元素,进行运算
int b=v.top(); v.pop();
int a=v.top(); v.pop();
if(ch=="+") v.push(a+b);
else if(ch=="-") v.push(a-b);
else if(ch=="*") v.push(a*b);
else{
v.push(a/b);
}
}
else{
//数字入栈
v.push(stoi(ch));//将字符转换成数字 方便运算
}
}
return v.top();
}
};

解法二:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
//也可以使用case语句
stack<int>v;
for(int i=0;i<tokens.size();i++)
{
string &str=tokens[i];
if(!("+" == str||" - " == str||" * " == str || "/ " == str))
{
v.push(atoi(str.c_str()));//int num = atoi(str.c_str());
}
else
{
int b=v.top(); v.pop();
int a=v.top(); v.pop();
switch(str[0])
{
case '+':
v.push(a+b);
break;
case '-':
v.push(a-b);
break;
case '*':
v.push(a*b);
break;
case '/':
v.push(a/b);
break;
}
}
}
return v.top();
}
};
扩展:



aoti文章转载处:aoti函数详解
如有错误,多多指教
边栏推荐
- Create function report error, prompting DECLARE definition syntax problem
- 2019年10月SQL注入的两倍
- utils timer
- Republish the lab report
- Optimize the query (work in progress)
- 云计算国内外发展现状
- HCIP BGP实验报告
- websocket多线程发送消息报错TEXT_PARTIAL_WRITING--自旋锁替换synchronized独占锁的使用案例
- Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
- 软测人每个阶段的薪资待遇,快来康康你能拿多少?
猜你喜欢

2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析

noip preliminary round

override学习(父类和子类)
![navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication](/img/09/a579c60e07cdc145175e72673409f7.png)
navicat 连接 mongodb 报错[13][Unauthorized] command listDatabases requires authentication

Boss: There are too many systems in the company, can you realize account interoperability?

FinClip,助长智能电视更多想象空间

Embedded Systems: GPIO

Deep integration of OPC UA and IEC61499 (1)

PowerMockup 4.3.4::::Crack

V8中的快慢数组(附源码、图文更易理解)
随机推荐
Analysys Analysis: The transaction scale of China's online retail B2C market in Q2 2022 will reach 2,344.47 billion yuan
【bug】汇总Elipse项目中代码中文乱码解决方法!
ML之yellowbrick:基于titanic泰坦尼克是否获救二分类预测数据集利用yellowbrick对LoR逻辑回归模型实现可解释性(阈值图)案例
工作小计 QT打包
《数字经济全景白皮书》金融数字用户篇 重磅发布!
Embedded Systems: Clocks
LabVIEW代码生成错误 61056
Gains double award | know micro easily won the "2021 China digital twin solution suppliers in excellence" "made in China's smart excellent recommended products" double award!
Redis persistence method
V8中的快慢数组(附源码、图文更易理解)
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
Unity2021发布WebGL雾效消失问题
Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
物联网新零售模式,引领购物新潮流
End-to-End Lane Marker Detection via Row-wise Classification
win10系统下yolov5-V6.1版本的tensorrt部署细节教程及bug修改
UVa 10003 - Cutting Sticks (White Book, Interval DP)
What is Adobe?
[2022强网杯] polydiv和gamemaster
log4j-slf4j-impl cannot be present with log4j-to-slf4j