与或式的真值表计算

 计算Y1,Y2的真值表:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// 计算变量的数目
int getVarNum(string str) {
    int cnt = 0;
    for (int i = 0; i < str.length(); i++) {
        if (islower(str[i])) {
            cnt = max(cnt, str[i] - 97);
        } else if (isupper(str[i])) {
            cnt = max(cnt, str[i] - 65);
        }
    }
    return cnt + 1;
}
// 分割字符串
vector<string> split(string str, char ch) {
    vector<string>s;
    int temp = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == ch) {
            s.push_back(str.substr(i - temp, temp));
            temp = 0;
        } else {
            temp++;
        }
    }
    s.push_back(str.substr(str.length() - temp, temp));
    return s;
}
void cal(string input) {
    vector<string>str = split(input, '+');
    int varNum = getVarNum(input);
    int total = 1 << varNum;
    for (int table = 0; table < total; table++) {
        bitset<8> b(table);
        int i = 0;
        for (i = varNum - 1; i >= 0; i--) {
            cout << b[i] << " ";
        }
        for (i = 0; i < str.size(); i++) {
            string v = str[i];
            int j = 0;
            for (j = 0; j < v.size(); j++) { // 有一个为0则v为0
                if (islower(v[j])) { // 是反变量
                    if (b[varNum - 1 - v[j] + 97] == 1) {
                        break;
                    }
                } else {
                    if (b[varNum - 1 - v[j] + 65] == 0) {
                        break;
                    }
                }
            }
            if (j >= v.size()) { // 都为1则v为1,且最终结果也为1
                break;
            }
        }
        if (i < str.size()) { // 有一个为1则最终结果为1
            cout << " " << 1 << endl;
        } else {
            cout << " " << 0 << endl;
        }
    }
    cout << endl;
}
int main() {
    string input;
    while (cin >> input) {
        cal(input);
    }
}

输入:

abC+aBc+Abc+ABC
BC+AC+AB

输出:

abC+aBc+Abc+ABC
0 0 0  0       
0 0 1  1       
0 1 0  1       
0 1 1  0       
1 0 0  1       
1 0 1  0       
1 1 0  0       
1 1 1  1       

BC+AC+AB       
0 0 0  0
0 0 1  0
0 1 0  0
0 1 1  1
1 0 0  0
1 0 1  1
1 1 0  1
1 1 1  1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值