给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。
注意:
数据保证给定的表达式合法。
题目保证符号 - 只作为减号出现,不会作为负号出现,例如,-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<bits/stdc++.h>
using namespace std;
stack<int> st1;
stack<char> st2;
void eval()
{
int b = st1.top(); st1.pop();
int a = st1.top(); st1.pop();
char op = st2.top(); st2.pop();
int t ;
if(op == '+') t = a+b;
else if(op == '-') t = a - b;
else if(op == '*') t = a * b;
else if(op == '/') t = a / b;
st1.push(t);
}
int main()
{
//优先级初始化
unordered_map<char, int> yxj{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
string str;
cin >> str;
int n = str.size();
for(int i=0; i<n; i++) {
//如果是数字
if(isdigit(str[i])) {
int x=0;
int j = i;
while(isdigit(str[j]) && j < n) {
x = x * 10 + (str[j] - '0');
j++;
}
i = j -1;
st1.push(x);
}
//如果是左括号
else if(str[i] == '(' ) st2.push(str[i]);
//如果是右括号
else if(str[i] == ')' ) {
while(st2.top() != '(') {
eval();
}
//左括号出栈
st2.pop();
}
// 如果是操作符
else {
while(!st2.empty() && st2.top() != '(' && yxj[st2.top()] >= yxj[str[i]]) {
eval();
}
st2.push(str[i]);
}
}
while(!st2.empty()) eval();
cout << st1.top() << endl;
return 0;
}