当前位置:网站首页>acwing 3302. 表达式求值
acwing 3302. 表达式求值
2022-07-04 19:13:00 【_刘小雨】
给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。
注意:
数据保证给定的表达式合法。
题目保证符号 - 只作为减号出现,不会作为负号出现,例如,-1+2,(2+2)*(-(1+1)+2) 之类表达式均不会出现。
题目保证表达式中所有数字均为正整数。
题目保证表达式在中间计算过程以及结果中,均不超过 231−1。
题目中的整除是指向 0 取整,也就是说对于大于 0 的结果向下取整,例如 5/3=1,对于小于 0 的结果向上取整,例如 5/(1−4)=−1。
C++和Java中的整除默认是向零取整;Python中的整除//默认向下取整,因此Python的eval()函数中的整除也是向下取整,在本题中不能直接使用。
输入格式
共一行,为给定表达式。
输出格式
共一行,为表达式的结果。
数据范围
表达式的长度不超过 105。
输入样例:
(2+2)*(1+1)
输出样例:
8
关键:
需要用两个栈, 一个栈用于保存数字,另一个需要保存操作运算符
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num; // 保存数字栈
stack<char> op; // 保存运算符栈
void eval()
{
auto b = num.top(); num.pop(); // 取数字
auto a = num.top(); num.pop(); // 取数字
auto c = op.top(); op.pop(); // 取运算符
int x;
// 计算
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
unordered_map<char, int> pr{
{
'+', 1}, {
'-', 1}, {
'*', 2}, {
'/', 2}}; // 如果有^, 可以直接在后面加 {'^',3}
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ )
{
auto c = str[i];
if (isdigit(c)) // 数字入栈
{
int x = 0, j = i;
while (j < str.size() && isdigit(str[j]))
x = x * 10 + str[j ++ ] - '0';
i = j - 1;
num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')')
{
while (op.top() != '(') eval(); // 一直需要计算到左括号
op.pop();
}
else
{
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval(); // 栈里面保存的优先级 >= 当前的优先级
op.push(c);
}
}
while (op.size()) eval();
cout << num.top() << endl;
return 0;
}
边栏推荐
- 左右最值最大差问题
- Automatic generation of interface automatic test cases by actual operation
- What financial products can you buy with a deposit of 100000 yuan?
- Is it safe for Great Wall Securities to open an account? Stock account opening process online account opening
- 复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算
- idea配置标准注释
- ICML 2022 | meta proposes a robust multi-objective Bayesian optimization method to effectively deal with input noise
- Qt编写物联网管理平台38-多种数据库支持
- 哈希(Hash)竞猜游戏系统开发功能分析及源码
- So this is the BGP agreement
猜你喜欢
随机推荐
针对深度学习的“失忆症”,科学家提出基于相似性加权交错学习,登上PNAS
阿里测试师用UI自动化测试实现元素定位
奏响青春的乐章
Automatic insertion of captions in word
What if win11u disk refuses access? An effective solution to win11u disk access denial
FS8B711S14电动红酒开瓶器单片机IC方案开发专用集成IC
Cdga | six principles that data governance has to adhere to
go笔记(1)go语言介绍以及特点
go语言笔记(2)go一些简单运用
字节测试工程师十年经验直击UI 自动化测试痛点
电脑怎么保存网页到桌面上使用
Six stones programming: about code, there are six triumphs
GVM使用
go笔记(3)Go语言fmt包的用法
Advantages of semantic tags and block level inline elements
Qt编写物联网管理平台38-多种数据库支持
Flet tutorial 07 basic introduction to popupmenubutton (tutorial includes source code)
实操自动生成接口自动化测试用例
What if the win11 shared file cannot be opened? The solution of win11 shared file cannot be opened
Après l'insertion de l'image dans le mot, il y a une ligne vide au - dessus de l'image, et la disposition est désordonnée après la suppression