C++中计算按位或结果为偶数的数对
给定一个整数数组,任务是计算可以使用给定数组值形成的数对总数,使得数对上的OR运算结果为偶数。
OR运算的真值表如下所示
| A | B | A∨B |
| 0 | 0 | 0 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 1 | 1 | 1 |
输入 − int arr[] = {2, 5, 1, 8, 9}
输出 − 按位或结果为偶数的数对个数为 − 2
解释 −
| a1 | a2 | a1∨a2 |
| 2 | 5 | 7 |
| 2 | 1 | 3 |
| 2 | 8 | 10 |
| 2 | 9 | 11 |
| 5 | 1 | 5 |
| 5 | 8 | 13 |
| 5 | 9 | 13 |
| 1 | 8 | 9 |
| 1 | 9 | 10 |
| 8 | 9 | 9 |
下面程序中使用的方案如下
输入一个整数元素数组以形成数对
计算数组的大小,并将数据传递给函数进行进一步处理。
创建一个临时变量count来存储以OR运算结果为偶数值形成的数对。
从i为0开始循环到数组大小
在循环内,检查IF arr[i] & 1 == FALSE,则将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] & 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 OR as Even number are: "<<count_pair(arr, size) << endl;
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count of pairs with Bitwise OR as Even number are: 3
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP