题目链接:Acwing 表达式求值
题面
给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。
注意:
数据保证给定的表达式合法。
题目保证符号 - 只作为减号出现,不会作为负号出现,例如,-1+2,(2+2)*(-(1+1)+2) 之类表达式均不会出现。
题目保证表达式中所有数字均为正整数。
题目保证表达式在中间计算过程以及结果中,均不超过 231−1。
题目中的整除是指向 0 取整,也就是说对于大于 0 的结果向下取整,例如 5/3=1,对于小于 0 的结果向上取整,例如 5/(1−4)=−1。
C++和Java中的整除默认是向零取整;Python中的整除//默认向下取整,因此Python的eval()函数中的整除也是向下取整,在本题中不能直接使用。
输入格式
共一行,为给定表达式。
输出格式
共一行,为表达式的结果。
数据范围
表达式的长度不超过 1e5。
输入样例:
(2+2)*(1+1)
输出样例:
8
代码:
//#pragma GCC optimize(2)
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#include<ctime>
#include<cstring>
#include<list>
#define ll long long
#define ull unsigned long long
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef pair<int, int> PII;
const int N = 1e6 + 7;
stack<int>num; //数字栈
stack<char>op; //符号栈
map<char, int>cmp = { {'+', 1}, { '-',1 }, { '*',2 }, { '/',2 }}; //给运算符号设定优先级
void eval() //执行两个数的运算操作
{
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char opr = op.top();
op.pop();
int x = 0;
if (opr == '+')x = a + b;
else if (opr == '-')x =a-b ;
else if (opr == '*')x =a*b ;
else if (opr == '/')x =a/b ;
num.push(x); //运算完后放回数字栈
}
void solve()
{
string s;
cin >> s;
for (int i = 0; i < s.size(); i++)
{
char c = s[i]; //取出字符
if (isdigit(c)) //如果是数字,就提取出数字放进数字栈
{
int j = i, x = 0;
while (j < s.size() && isdigit(s[j]))
x = x * 10 + s[j++] - '0';
num.push(x);
i = j - 1;
}
else if (c == '(') op.push(c); //左括号直接放进符号栈
else if (c == ')') //遇到右括号先算括号里面的
{
while (op.size() && op.top() != '(') eval();
op.pop();
}
else //遇到运算符就通过比较优先级来进行运算
{
while (op.size() && cmp[op.top()] >= cmp[c]) eval();
op.push(c);
}
}
while (op.size()) eval(); //最后把所有运算算完
cout << num.top() << endl;//输出最后结果
}
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
solve();
return 0;
}
作者:Avalon Demerzel