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}
输出 − 按位与结果为偶数的对数为 - 7
解释 −
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 开始循环到数组的大小
在循环内,检查 IF arr[i] % 2 == FALSE,则将 count 加 1
将 count 设置为 count * (count - 1) / 2
创建一个临时变量来存储形成的对的总数,并将其设置为 (size * (size - 1) / 2)
将奇数存储为从形成的对的总数中减去 count
返回奇数值
打印结果。
示例
#include <iostream> using namespace std; //Count pairs with Bitwise AND as EVEN number int count_pair(int arr[], int size){ int count = 0; for (int i = 0; i < size; i++){ if (arr[i] % 2 != 0){ count++; } } count = count * (count - 1) / 2; int total_pair = (size * (size - 1) / 2); int odd = total_pair - count; return odd; } int main(){ int arr[] = {2, 5, 1, 8, 3 }; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of pairs with Bitwise-AND as even 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 even number are: 7
广告