C++ 中按位与运算结果为奇数的数对计数
给定一个整数数组,任务是计算可以使用给定数组值形成的所有数对的总数,使得数对上的 AND 运算结果为奇数。
AND 运算的真值表如下所示
A | B | A^B |
0 | 0 | 0 |
1 | 0 | 0 |
0 | 1 | 0 |
1 | 1 | 1 |
输入 − int arr[] = {2, 5, 1, 8, 9}
输出 − 按位与运算结果为奇数的数对个数为 − 3
解释 −
a1 | a2 | a1^a2 |
2 | 5 | 0 |
2 | 1 | 0 |
2 | 8 | 0 |
2 | 9 | 0 |
5 | 1 | 1 |
5 | 8 | 0 |
5 | 9 | 1 |
1 | 8 | 0 |
1 | 9 | 1 |
8 | 9 | 8 |
下面程序中使用的方案如下
输入一个整数元素数组以形成数对
计算数组大小,并将数据传递给函数进行进一步处理。
创建一个临时变量 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
广告