当前位置:网站首页>逆波兰表达式求值
逆波兰表达式求值
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函数详解
如有错误,多多指教
边栏推荐
- 【day1】
- Live Preview | Build Business Intelligence, Quickly Embrace Financial Digital Transformation
- Basic Concepts of Graphs
- golang写的存储引擎,基于b+树,mmap
- P1996 约瑟夫问题
- [MySQL Advanced] Creation and Management of Databases and Tables
- 【MySQL进阶】数据库与表的创建和管理
- 113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
- node连接mysql数据库报错:Client does not support authentication protocol requested by server
- HCIP BGP实验报告
猜你喜欢
Adobe是什么?
redis持久化方式
HCIP BGP lab report
完全二叉树问题
代码随想录笔记_动态规划_416分割等和子集
物联网新零售模式,引领购物新潮流
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
重发布实验报告
Another MySQL masterpiece published by Glacier (send the book at the end of the article)!!
七夕活动浪漫上线,别让网络拖慢和小姐姐的开黑时间
随机推荐
Kotlin - extension functions and operator overloading
Fluorescein-PEG-CLS,胆固醇-聚乙二醇-荧光素科研试剂
重发布实验报告
【MySQL进阶】数据库与表的创建和管理
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
Embedded Systems: GPIO
113. Teach a Man how to fish - How to query the documentation and technical implementation details of any SAP UI5 control property by yourself
Zilliz 2023 Fall Campus Recruitment Officially Launched!
With the rise of concepts such as metaverse and web3.0, many digital forms such as digital people and digital scenes have begun to appear.
藏宝计划TreasureProject(TPC)系统模式开发技术原理
设置工作模式与环境(下):探查和收集信息
2019年10月SQL注入的两倍
2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析
易观分析:2022年Q2中国网络零售B2C市场交易规模达23444.7亿元
complete binary tree problem
Work Subtotal QT Packing
云计算国内外发展现状
雅思大作文写作模版
[RYU] rest_router.py source code analysis
为什么我们需要回调