当前位置:网站首页>逆波兰表达式求值
逆波兰表达式求值
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函数详解
如有错误,多多指教
边栏推荐
- 云平台建设解决方案
- The sword refers to the offer question 22 - the Kth node from the bottom in the linked list
- utlis 线程池
- Scala basics [regular expressions, framework development principles]
- What is Adobe?
- The development status of cloud computing at home and abroad
- Optimize the query (work in progress)
- Testng监听器
- Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
- RPA助力商超订单自动化!
猜你喜欢
Causes of Mysql Disk Holes and Several Ways to Rebuild Tables
物联网新零售模式,引领购物新潮流
最小化安装debian11
What is the difference between the generator version and the viewer version?
Lift, Splat, Shoot: Encoding Images from Arbitrary Camera Rigs by Implicitly Unprojecting to 3D 论文笔记
V8中的快慢数组(附源码、图文更易理解)
.NET6之MiniAPI(十四):跨域CORS(上)
Diazo Biotin-PEG3-DBCO | Diazo Compound Modified Biotin-Tripolyethylene Glycol-Dibenzocyclooctyne
Recognized by International Authorities | Yunzhuang Technology was selected in "RPA Global Market Pattern Report, Q3 2022"
"Digital Economy Panorama White Paper" Financial Digital User Chapter released!
随机推荐
PowerMockup 4.3.4::::Crack
[2022强网杯] polydiv和gamemaster
Embedded systems: overview
物联网新零售模式,引领购物新潮流
目标检测的国内外研究现状
Canvas App中点击图标生成PDF并保存到Dataverse中
创建函数报错,提示DECLARE定义语法问题
HCIP BGP lab report
Software testing is seriously involution, how to improve your competitiveness?
【RYU】rest_router.py源码解析
伴随着元宇宙、web3.0等概念的兴起,数字人、数字场景等诸多数字化的形态开始出现
golang写的存储引擎,基于b+树,mmap
V8中的快慢数组(附源码、图文更易理解)
What is memoization and what is it good for?
encapsulation, package, access modifier, static variable
雅思大作文写作模版
冰河又一MySQL力作出版(文末送书)!!
MCS-51单片机,定时1分钟,汇编程序
二叉搜索树解决落叶问题
设置工作模式与环境(下):探查和收集信息