在C ++中将按位与的偶数计数为偶数
给我们一个整数数组,任务是计算使用给定数组值可以形成的对的总数,这样对对的AND操作将得出偶数。
AND运算的真值表如下所示
输入−intarr[]={2,5,1,8,9}
输出-按位与为偶数的对数为-7
说明-
以下程序中使用的方法如下
输入整数元素数组以形成一对
计算数组的大小,将数据传递给函数以进行进一步处理
创建一个临时变量计数以将与AND运算形成的对存储为偶数。
从i到0开始循环直到数组大小
在循环内部,检查IFarr[i]%2==FALSE,然后将计数加1
将计数设置为count*(count-1)/2
创建一个临时变量以存储形成的对的总数,并将其设置为(size*(size-1)/2)
存储奇数作为从形成的对总数中减去的计数
返回奇数值
打印结果。
示例
#include <iostream>
using namespace std;
//用按位AND作为偶数来计数对
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;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs with Bitwise-AND as even number are: 7
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便