C++中数组所有元素的异或运算(集合位数等于K)
在这个问题中,我们给定一个包含n个元素的数组和一个整数值k。我们的任务是找到所有集合位数等于k的数组元素的异或值。
让我们来看一个例子来理解这个问题:
输入
array = {2, 12, 44, 103, 17} , K =3输出
44
为了解决这个问题,我们将计算数组中每个元素的集合位数,并将其与k进行比较。如果集合位数等于k,则将其推入向量,并找到向量中所有元素的异或值。
为了查找集合位数,我们将使用`__builtin_popcount()`,这是C++中的一个内置函数。
展示我们解决方案实现的程序:
示例
#include <bits/stdc++.h>
using namespace std;
int XorKSetBits(int arr[], int n, int k){
vector<int> kBitElments;
for (int i = 0; i < n; i++) {
if (__builtin_popcount(arr[i]) == k) {
kBitElments.push_back(arr[i]);
}
}
int result = kBitElments[0];
for (int i = 1; i < kBitElments.size(); i++)
result ^= kBitElments[i];
return result;
}
int main(){
int arr[] = { 2, 12, 44, 103, 17 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
cout<<"XOR of all element of the array with "<<k<<" set bits is : "<<XorKSetBits(arr, n, k);
return 0;
}输出
XOR of all element of the array with 3 set bits is : 44
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP