C++ 中计算按位异或结果为奇数的配对数量
给定一个整数数组,任务是计算可以使用给定数组值形成的所有配对的总数,使得配对上的异或运算结果为奇数。
异或运算的真值表如下所示
A | B | A XOR B |
0 | 0 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
1 | 1 | 0 |
输入 − int arr[] = {2, 8, 1, 5, 11}
输出 − 按位异或结果为奇数的配对数量为 - 6
解释
解释 −
a1 | a2 | a1 XOR a2 |
2 | 8 | 10 |
2 | 1 | 3 |
2 | 5 | 7 |
2 | 11 | 9 |
8 | 1 | 9 |
8 | 5 | 13 |
8 | 11 | 3 |
1 | 5 | 4 |
1 | 11 | 10 |
5 | 11 | 14 |
下面程序中使用的方案如下
输入一个整数元素数组来形成配对
计算数组的大小,并将数据传递给函数以进行进一步处理。
创建一个临时变量 count 来存储形成的配对,其异或运算结果为奇数。
从 i=0 开始循环 FOR,直到数组的大小。
现在计算数组中奇数配对的数量为 count * (size - count)。
返回奇数
打印结果
示例
#include <iostream> using namespace std; //Count pairs with Bitwise XOR as ODD number int XOR_Odd(int arr[], int size){ int count = 0; for (int i = 0; i < size; i++){ if (arr[i] % 2 == 0){ count++; } } int odd = count * (size-count); return odd; } int main(){ int arr[] = { 6, 1, 3, 4, 8, 9}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of pairs with Bitwise XOR as ODD number are: "<<XOR_Odd(arr, size); return 0; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果我们运行以上代码,它将生成以下输出:
Count of pairs with Bitwise XOR as ODD number are: 9
广告