计算数组中的对,以使两个元素在C ++中具有相等的置位位
给我们一个整数类型元素的数组,任务是从给定的数组中形成对,并计算该对中元素的设置位,并检查两个元素是否具有相等数量的设置位。
二进制数中的设置位用1表示。每当我们计算一个整数值的二进制数时,它就会形成为0和1的组合。因此,数字1在计算机方面称为设置位。
输入值
int arr[] = {6, 5, 1, 3, 7}
输出结果
Count of pairs in an array such that both elements has equal set bits are: 3
说明
The pairs formed from the given array are-: (6, 5): 6 -> 2 set bits, 5 -> 2 set bits :(valid pair) (6, 5): 6 -> 2 set bits, 1 -> 1 set bit:(invalid pair) (6, 3): 6 -> 2 set bits, 3 -> 2 set bits :(valid pair) (6, 7): 6 -> 2 set bits, 7 -> 3 set bits :(invalid pair) (5, 1): 5 -> 2 set bits, 1 -> 1 set bits :(invalid pair) (5, 3): 5 -> 2 set bits, 3 -> 2 set bits :(valid pair) (5, 1): 5 -> 2 set bits, 7 -> 3 set bits :(invalid pair) (1, 3): 1 -> 1 set bits, 3 -> 2 set bits :(invalid pair) (1, 3): 1 -> 1 set bits, 7 -> 3 set bits :(invalid pair) (3, 7): 3 -> 2 set bits, 7 -> 3 set bits :(invalid pair) So, there are 3 valid pairs with equal number of set bits and those are (6, 5), (6, 3) and (5, 2)
输入值
int arr[] = {4, 6, 3, 2}
输出结果
Count of pairs in an array such that both elements has equal set bits are: 3
说明
The pairs formed from the given array are-: (4, 6): 4 -> 1 set bits, 6 -> 2 set bits :(invalid pair) (4, 3): 4 -> 1 set bits, 3 -> 2 set bits :(invalid pair) (4, 2): 4 -> 1 set bits, 2 -> 1 set bits :(valid pair) (6, 3): 6 -> 2 set bits, 3 -> 2 set bits :(valid pair) (6, 2): 6 -> 2 set bits, 2 -> 1 set bits :(invalid pair) (3, 2): 3 -> 2 set bits, 2 -> 1 set bits :(invalid pair) So, there are 2 valid pairs with equal number of set bits and those are (4, 2) and (6, 3).
以下程序中使用的方法如下
输入一个整数元素数组并计算数组的大小并将数据传递给函数
声明一个临时变量计数,以存储具有相等设置位数的对的计数。
从i到0开始循环直到数组大小
在循环内,从j到i+1开始另一个循环,直到数组大小
在循环内部,通过调用函数“__builtin_popcount(element)”将一对中的第一个和第二个元素设置为设置位的总数,该函数返回整数的设置位的总数。
检查一对的第一个和第二个元素的IF设置位是否相等,然后将计数加1
返回计数
打印结果。
示例
#include <iostream> using namespace std; int pair_setBit(int arr[], int size){ int count = 0; for(int i = 0 ;i <size ; i++){ for(int j = i+1; j<size; j++){ int first = __builtin_popcount(arr[i]); int second = __builtin_popcount(arr[j]); if(first == second){ count++; } } } return count; } int main(){ int arr[] = {6, 5, 1, 3, 7}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Count of pairs in an array such that both elements has equal set bits are: "<<pair_setBit(arr, size); return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of pairs in an array such that both elements has equal set bits are: 3