力扣算法题—150. Evaluate Reverse Polish Notation
2024-09-06 06:02:24
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example 1:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22 Solution:
使用栈即可
class Solution {
public:
int evalRPN(vector<string> &tokens) {
if (tokens.size() == )return ;
stack<int>s;
for (auto a : tokens)
{
if (a == "+" || a == "-" || a == "*" || a == "/")
{
int num2 = s.top();
s.pop();
int num1 = s.top();
s.pop();
int res = ;
if (a == "+")
res = num1 + num2;
else if (a == "-")
res = num1 - num2;
else if (a == "*")
res = num1 * num2;
else
res = num1 / num2;
s.push(res);
}
else
s.push(atoi(a.c_str()));
}
return s.top();
}
};
最新文章
- Hadoop学习笔记—7.计数器与自定义计数器
- 根据字体计算CGRect
- 算法系列:寻找最大的 K 个数
- 【XLL API 函数】xlSheetNm
- Reveal使用步骤和 破解Revealapp的试用时间限制
- iOS 上拉刷新和下拉加在更多(第三方框架EGOTableViewPullRefresh)
- javascript中set与get方法详解
- 新浪微博开放平台OAuth授权解决方案(含代码)
- uva 103 Stacking Boxes(DAG)
- HTML 5入门知识(五)
- 【2017-03-30】JS-document对象
- RE:考勤系统的复盘
- Python 学习之路2
- RSA加解密实现
- logback打印日志时添加上下文
- XSS(笔记1)
- Python学习—基础篇之常用模块
- [Jenkins][git]构建时提示Caused by: hudson.plugins.git.GitException: Command ";/usr/bin/git reset --hard"; returned status code 128:
- C++ 开源库列表
- 转:SqlServer索引及优化详解
热门文章
- java的继承 和super关键字 构造器
- 从源码导入到github
- Linux用ifconfig设置IP、掩码、网关
- POJ 2254 Globetrotter (计算几何 - 球面最短距离)
- Rust <;7>;:数据结构==>;链表
- SpringBoot+Thymeleaf+iView
- 【python标准库学习】thread,threading(一)多线程的介绍和使用
- tomcat部署项目后,项目没有成功部署到tomcat里面,或者部署的是之前项目
- groupby 技术
- google cloud