C++ 中按位与运算结果为奇数的数对计数


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

AND 运算的真值表如下所示

ABA^B
000
100
010
111

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

输出 − 按位与运算结果为奇数的数对个数为 − 3

解释

a1a2a1^a2
250
210
280
290
511
580
591
180
191
898

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

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

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

  • 创建一个临时变量 count 来存储以 AND 运算为奇数值形成的数对。

  • 从 i 为 0 开始循环到数组大小

  • 在循环内,如果 arr[i] % 2 == TRUE,则将 count 加 1

  • 将 count 设置为 count * (count - 1) / 2

  • 返回 count

  • 打印结果。

示例

 在线演示

#include <iostream>
using namespace std;
//Count pairs with Bitwise AND as ODD number
int count_pair(int arr[], int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      if ((arr[i] % 2 == 1)){
         count++;
      }
   }
   count = count * (count - 1) / 2;
   return count;
}
int main(){
   int arr[] = {2, 5, 1, 8, 9, 2, 7};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs with Bitwise AND as ODD number are: "<<count_pair(arr, size) << endl;
   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 AND as ODD number are: 6

更新于:2020年8月31日

102 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告