当前位置:网站首页>逆波兰表达式求值
逆波兰表达式求值
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函数详解
如有错误,多多指教
边栏推荐
- Interpretation of ML: A case of global interpretation/local interpretation of EBC model interpretability based on titanic titanic rescued binary prediction data set using interpret
- Software testing is seriously involution, how to improve your competitiveness?
- Boss: There are too many systems in the company, can you realize account interoperability?
- 《数字经济全景白皮书》金融数字用户篇 重磅发布!
- First domestic open source framework 】 【 general cloud computing framework, any program can be made into cloud computing.
- 2022-08-03 oracle执行慢SQL-Q17对比
- Cloud platform construction solutions
- 电商秒杀系统
- 【论文阅读】TRO 2021: Fail-Safe Motion Planning for Online Verification of Autonomous Vehicles Using Conve
- .NET6之MiniAPI(十四):跨域CORS(上)
猜你喜欢

软件测试内卷严重,如何提升自己的竞争力呢?

2022-08-03 Oracle executes slow SQL-Q17 comparison

Live Preview | Build Business Intelligence, Quickly Embrace Financial Digital Transformation

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!

软测人每个阶段的薪资待遇,快来康康你能拿多少?

2022-08-03 oracle执行慢SQL-Q17对比

encapsulation, package, access modifier, static variable

设置工作模式与环境(下):探查和收集信息

PowerMockup 4.3.4::::Crack

静态文件快速建站
随机推荐
for loop exercises
Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂
The development status of cloud computing at home and abroad
Adobe是什么?
FinClip,助长智能电视更多想象空间
P1449 后缀表达式
Conditional Statements for Shell Programming
《数字经济全景白皮书》金融数字用户篇 重磅发布!
电商秒杀系统
What is the difference between the generator version and the viewer version?
冰河又一MySQL力作出版(文末送书)!!
目标检测技术研究现状及发展趋势
Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
3D 语义分割——2DPASS
Causes of Mysql Disk Holes and Several Ways to Rebuild Tables
云平台建设解决方案
RPA power business automation super order!
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
Optimize the query (work in progress)
使用tf.image.resize() 和tf.image.resize_with_pad()调整图像大小