在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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短