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 开始循环到数组大小

  • 在循环内部,如果 arr[i] % 2 == FALSE,则将 even_XOR 加 1,否则将 odd_XOR 加 1。

  • 现在将 count 设置为 odd_XOR * even_XOR

  • 返回 count

  • 打印结果

示例

 在线演示

#include <iostream>
using namespace std;
//Count pairs with Odd XOR
int Odd_XOR(int arr[], int size){
   int count = 0;
   int odd_XOR = 0;
   int even_XOR = 0;
   for (int i = 0; i < size; i++){
      if (arr[i] % 2 == 0){
         even_XOR++;
      }
      else{
         odd_XOR++;
      }
   }
   count = odd_XOR * even_XOR;
   return count;
}
int main(){
   int arr[] = { 2, 6, 1, 4 };
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with Odd XOR are: "<<Odd_XOR(arr, size);
   return 0;
}

输出

如果运行以上代码,将生成以下输出:

Count of pairs with Odd XOR are: 3

更新于:2020年8月31日

浏览量 155

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.