C++ 中计算按位异或结果为奇数的配对数量


给定一个整数数组,任务是计算可以使用给定数组值形成的所有配对的总数,使得配对上的异或运算结果为奇数。

异或运算的真值表如下所示

ABA XOR B
000
101
011
110

输入 − int arr[] = {2, 8, 1, 5, 11}

输出 − 按位异或结果为奇数的配对数量为 - 6

解释

解释

a1a2a1 XOR a2
2810
213
257
2119
819
8513
8113
154
11110
51114

下面程序中使用的方案如下

  • 输入一个整数元素数组来形成配对

  • 计算数组的大小,并将数据传递给函数以进行进一步处理。

  • 创建一个临时变量 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

更新于:2020-08-31

163 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告