2024牛客国庆集训派对day5_xay loves or——位运算

考点:或运算的应用

题目描述

xay loves or. He gives you x and s, you need to calculate how many positive integer y satisfy x or ⁡y = s .

输入描述:

The first line contains two positive integers x and s .

It's guaranteed that 1 ≤x,s< 2^31.

输出描述:

Print the number of y satisfy x or ⁡y = s .

示例1

输入

2 5

输出

0

原题链接:I-xay loves or_2024牛客国庆集训派对day5

题解:

#include <iostream>

using namespace std;

/*
x s
1 1 此时该位y可变,可0可1
0 1 此时该位y固定为1
1 0 此时x没法通过|掰正为0,无解
0 0 此时该位y固定为0

*/
long long pd(int x, int s) {
    if ((x | s) != s) {  // 如果 x 的某些位为 1,而 s 的对应位为 0,则无解
        return 0;
    }

    int count = 0;
    // 遍历 s 的每一位
    for (int i = 0; i < 32; ++i) {  // 检查 32 位
        if ((s >> i) & 1) {  // s 的第 i 位是 1
            if ((x >> i) & 1) {  // x 的第 i 位也是 1
                count++;  // 该位可以自由选择 0 或 1
            }
        }/* else {  // s 的第 i 位是 0
            if ((x >> i) & 1) {  // 如果 x 的第 i 位是 1,则无解
                return 0;
            }
        }*///已经在最开始的(x | s) != s处判断了s是0,x是1的情况,此处为了逻辑清晰补上的
    }

    // 如果 x 和 s 完全一致,则结果应为 2^count - 1
    if (x == s) {
        return (1LL << count) - 1;
    }
    
    // 返回 2^count 表示所有可能的组合
    return 1LL << count;
}

int main() {
    int x, s;
    cin >> x >> s;
    long long res = pd(x, s);
    cout << res << endl;
    return 0;
}

1LL << count 是2^count的意思,为了防止大数溢出,特意把1变LL,即long long类型

(x | s) != s是因为如果有s位是0,x位是1,则等式不成立,立即无解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值