当前位置:网站首页>Leetcode 150. 逆波兰表达式求值
Leetcode 150. 逆波兰表达式求值
2022-07-17 15:36:00 【LuZhouShiLi】
Leetcode 150. 逆波兰表达式求值
题目

思路
- 扫描后缀表达式,遇到数字就将其入栈
- 当扫描到运算符时,将栈顶的两个元素取出来进行运算,然后将结果存入栈中
代码
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
// 遇到运算符 取出两个栈顶元素进行运算 将结果放回栈中
int num1 = st.top();// 取出栈顶元素
st.pop();// 出栈
int num2 = st.top();
st.pop();
if(tokens[i] == "+") st.push(num1 + num2);
if(tokens[i] == "-") st.push(num2 - num1);
if(tokens[i] == "*") st.push(num1 * num2);
if(tokens[i] == "/") st.push(num2 / num1);
}
else
{
st.push(stoi(tokens[i]));
}
}
int result = st.top();
st.pop();// 把栈里最后一个元素弹出
return result;
}
};
边栏推荐
- 【机器学习】多标签分类的评价指标与代码实现
- From prediction to decision-making, Chapter 9 Yunji datacanvas launched the ylearn causal learning open source project
- C语言绘图示例-繁花图案
- Flink
- 梦想CMS 前台搜索SQL注入
- Flink
- Huawei firewall authentication technology
- 02-3、指针和引用的区别
- Leetcode 1310. Subarray XOR query
- Nintendo patent shows that the follow-up products of fitness ring accessories may be under development
猜你喜欢

Redis Distributed cache - Redis Cluster

【二叉树】之力扣牛客必刷题

使用原生js实现按钮的全选功能,简单清晰

Cv02 Roge matrix, rotation vector, angle
![[wechat applet] use a thousand hand float - rollback](/img/52/4939ff2a644c46fdb388a64ac111c6.png)
[wechat applet] use a thousand hand float - rollback

【机器学习】多标签分类的评价指标与代码实现

High performance IO framework library libevent (III): overview of libevent framework functions

C语言绘图示例-调色板

Send blocking, receive blocking

MGRE 环境下配置OSPF实验
随机推荐
渐变色按钮功能按钮绘制C语言示例
Conversion between Swift binary data and hexadecimal string
Automated graphical interface library pyautogui
LeetCode_77_组合
TiDB 内存控制文档
[original] magisk+shamiko has been tested by app root
[unity technology accumulation] simple timer & Co process & delay function
HCIP(8)
Detailed explanation of MySQL show processlist
Push down calculation result cache
Stc8h development (XIV): I2C drive rx8025t high-precision real-time clock chip
03-2、
Three. JS basic element usage
Introduction and Simulation Implementation of string class
Fundamentals of scala (3): operators and process control
C语言绘图示例-商标徽标
STL string input / output overload 2
02-2. Default parameters, function overloading, reference, implicit type conversion, about error reporting
02-3、指針和引用的區別
Mysql5.6 alter statement