考点:或运算的应用
题目描述
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
题解:
#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,则等式不成立,立即无解