题目大意:
模拟一个二进制位运算计算器,给定T行二进制下的操作序列,对于每行操作,输出计算得到的值。共有两类操作运算符,一元运算符not(取反),shr(右移),shl(左移),二元运算符and(且),or(或),xor(异或)。一元运算符的运算优先级高于二元运算符,二元运算符的优先级一致,需从左到右依次计算。
每次读入一个数判断是否还有操作符,把其之前的操作符从后往前运算掉,最后输出规格化结果(不含前导零)
AC代码如下:
- #include <bits/stdc++.h>
- using namespace std;
- stack<string> ops;
- string formatNumber(string s) {
- while (!s.empty() && *s.begin() == '0')
- s.erase(s.begin());
- if (s.empty())
- s = "0";
- return s;
- }
- void judge(string n) {
- while (!ops.empty()) {
- string op = ops.top();
- ops.pop();
- if (op == "not") {
- n = formatNumber(n);
- for (int i = 0; i < n.size(); ++i)
- n[i] = (n[i] == '0') ? '1' : '0';
- }
- else if (op == "shr") {
- n = formatNumber(n);
- if (!n.empty())
- n.pop_back();
- }
- else if (op == "shl") {
- n = formatNumber(n);
- n.push_back('0');
- }
- else {
- string m = ops.top();
- ops.pop();
- while (m.size() < n.size()) m = "0" + m;
- while (n.size() < m.size()) n = "0" + n;
- if (op == "xor") {
- for (int i = 0; i < n.size(); ++i)
- n[i] = (n[i] == m[i]) ? '0' : '1';
- }
- else if (op == "and") {
- for (int i = 0; i < n.size(); ++i)
- n[i] = (n[i] == '1' && m[i] == '1') ? '1' : '0';
- }
- else {
- for (int i = 0; i < n.size(); ++i)
- n[i] = (n[i] == '1' || m[i] == '1') ? '1' : '0';
- }
- }
- }
- ops.push(n);
- }
- int main() {
- int T;
- scanf("%d", &T);
- string str;
- int cas = 1;
- while (T--) {
- while (!ops.empty())
- ops.pop();
- while (true)
- {
- cin >> str;
- char ch = getchar();
- if (str[0] == '1' || str[0] == '0')
- judge(str); // number
- else
- ops.push(str); // operator
- if (ch == ' ')
- break;
- }
- printf("Case %d: ", cas++);
- cout << formatNumber(ops.top()) << endl;
- }
- return 0;
- }