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}
输出 − 按位异或结果为偶数的数对个数为 − 4
解释 −
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开始循环到数组的大小
在循环内,如果arr[i] % 2 == 0,则将count加1
将temp设置为size * (size - 1)
设置另一个临时变量pairs = temp / 2
现在计算数组中奇数对的数量为count * (size - count)
现在计算偶数对的数量为总对数 - 奇数对数
返回偶数对的数量
打印结果。
示例
#include <iostream> using namespace std; //Count pairs with Bitwise XOR as EVEN number int XOR_Even(int arr[], int size){ int count = 0; for (int i = 0; i < size; i++){ if (arr[i] % 2 != 0){ count++; } } int temp = size * (size-1); int Pairs = temp / 2; int odd = count * (size - count); int even = Pairs - odd; return even; } int main(){ int arr[] = { 2, 6, 1, 8}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of pairs with Bitwise XOR as EVEN number are: "<<XOR_Even(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 EVEN number are: 3
广告