
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
XOR of all elements of array with set bits equal to K in C++
In this problem, we are given an array of n elements and an integer value k. Our task is to find XOR of all elements of the array that have set bits equal to k.
Let’s take an example to understand the problem,
Input
array = {2, 12, 44, 103, 17} , K =3
Output
44
To solve this problem, we will count set bit of every element of the array and compare it with k. If the number of set bits is equal to k, then we will push it to a vector and find XOR of all elements of the vector.
For finding the set bit count we will use __builtin_popcount() which is a built-in function in c++.
Program to show the implementation of our solution,
Example
#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; }
Output
XOR of all element of the array with 3 set bits is : 44
- Related Articles
- Maximum number of contiguous array elements with same number of set bits in C++
- Count pairs in an array such that both elements has equal set bits in C++
- Count all pairs of an array which differ in K bits in C++
- Find all combinations of k-bit numbers with n bits set where 1
- Count minimum bits to flip such that XOR of A and B equal to C in C++
- Minimizing array sum by applying XOR operation on all elements of the array in C++
- Find elements of array using XOR of consecutive elements in C++
- Construct an array from XOR of all elements of array except element at same index in C++
- Minimum flips required to maximize a number with k set bits in C++.
- Count of element in an array whose set bits are in a multiple of K
- Sort an array according to count of set bits in C++
- Sum of XOR of all pairs in an array in C++
- XOR of all Prime numbers in an Array in C++
- Minimum operation to make all elements equal in array in C++
- Find the number of operations required to make all array elements Equal in C++

Advertisements