输入一个表达式的字符串,只包含0、1、|、&、!、(、)七种字符,然后输出表达式的结果,保证输入合法。!优先级大于&大于|。
这题有个需要注意的点就是:!是一元运算符,这里考虑两种情况,如果!后面是数字,就直接进行运算,并将运算结果入栈。如果!后面是(,就将!压进符号栈,在(出栈时判断当前栈顶是否为!,若为!,将数字栈中的栈顶元素弹出进行!运算。
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<vector>
#include<stack>
#include<sstream>
#include<unordered_map>
using namespace std;
stack<char>op;
stack<int>sn;
unordered_map<char, int>p_map;
int main() {
p_map['('] = 0;
p_map['|'] = 1;
p_map['&'] = 2;
string s;
cin >> s;
int len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] == '0' || s[i] == '1') {
int tmp = s[i] - '0';
sn.push(tmp);
}
else if (s[i] == '!') {
if (s[i + 1] == '0' || s[i + 1] == '1') {
i++;
int tmp = s[i] - '0';
sn.push(!tmp);
}
else if (s[i + 1] == '(') {
op.push(s[i]);
}
}
else if (s[i] == '(') {
op.push(s[i]);
}
else if (s[i] == ')') {
while (op.top() != '(') {
char c = op.top();
op.pop();
int n1 = sn.top();
sn.pop();
int n2 = sn.top();
sn.pop();
if (c == '|')
sn.push(n1 | n2);
else if (c == '&')
sn.push(n1&n2);
}
op.pop();
if (!op.empty() && op.top() == '!') {
op.pop();
int num = sn.top();
sn.pop();
sn.push(!num);
}
}
else {
if (!op.empty()) {
while (!op.empty() && p_map[s[i]] < p_map[op.top()]) {
char c = op.top();
op.pop();
int n1 = sn.top();
sn.pop();
int n2 = sn.top();
sn.pop();
if (c == '|') {
sn.push(n1 | n2);
}
else if (c == '&') {
sn.push(n1 & n2);
}
}
op.push(s[i]);
}
else {
op.push(s[i]);
}
}
}
while (!op.empty()) {
char c = op.top();
op.pop();
int n1 = sn.top();
sn.pop();
int n2 = sn.top();
sn.pop();
if (c == '|')
sn.push(n1 | n2);
else if(c=='&')
sn.push(n1 & n2);
}
cout << sn.top();
return 0;
}