Enter the string of an expression, which contains only seven characters: 0, 1, |, &,!, (,) and then output the result of the expression to ensure that the input is legitimate. Priority is greater than & greater than |.
There is a point to be noted in this question: 1. Is a unary operator, here consider two cases, if! After that is the number, the operation is carried out directly, and the result of the operation is put on the stack. If! The following is (, will! Press into the symbol stack and determine whether the current top of the stack is! If so! To pop up the top element of the stack in the digital stack! Operation.
Code:
#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; }