Related Articles
XOR of all elements of array with set bits equal to K
• Difficulty Level : Basic
• Last Updated : 22 May, 2019

Given an array of integers and a number K. The task is to find the XOR of only those elements of the array whose total set bits are equal to K.

Examples:

```Input : arr[] = {1, 22, 3, 10}, K=1
Output : 1
Elements with set bits equal to 1 is 1.
So, XOR is also 1.

Input : arr[] = {3, 4, 10, 5, 8}, K=2
Output : 12
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

1. Initialize an empty vector.
2. Traverse the array form left to right and check the set bits of each element.
3. Use, C++ inbuilt function __builtin_popcount() to count setbits.
4. Push the elements with K setbits into the vector.
5. Finally find XOR of all the elements of the vector.

Below is the implementation of the above approach:

## C++

 `// C++ program to find Xor``// of all elements with set bits``// equal to K``#include ``using` `namespace` `std;`` ` `// Function to find Xor``// of desired elements``int` `xorGivenSetBits(``int` `arr[], ``int` `n, ``int` `k)``{``    ``// Initialize vector``    ``vector<``int``> v;`` ` `    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(__builtin_popcount(arr[i]) == k) {``            ``// push required elements``            ``v.push_back(arr[i]);``        ``}``    ``}`` ` `    ``// Initialize result with first element of vector``    ``int` `result = v;`` ` `    ``for` `(``int` `i = 1; i < v.size(); i++)``        ``result = result ^ v[i];`` ` `    ``return` `result;``}`` ` `// Driver code``int` `main()``{``    ``int` `arr[] = { 2, 13, 1, 19, 7 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `k = 3;`` ` `    ``cout << xorGivenSetBits(arr, n, k);`` ` `    ``return` `0;``}`

## Java

 `// Java program to find Xor``// of all elements with set bits``// equal to K``import` `java.util.*;`` ` `class` `GFG``{`` ` `    ``// Function to find Xor``    ``// of desired elements``    ``static` `int` `xorGivenSetBits(``int` `arr[], ``                                ``int` `n, ``int` `k)``    ``{``        ``// Initialize vector``        ``Vector v = ``new` `Vector<>();`` ` `        ``for` `(``int` `i = ``0``; i < n; i++) ``        ``{``            ``if` `(Integer.bitCount(arr[i]) == k)``            ``{``                ``// push required elements``                ``v.add(arr[i]);``            ``}``        ``}`` ` `        ``// Initialize result with first element of vector``        ``int` `result = v.get(``0``);`` ` `        ``for` `(``int` `i = ``1``; i < v.size(); i++) ``        ``{``            ``result = result ^ v.get(i);``        ``}`` ` `        ``return` `result;``    ``}`` ` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) ``    ``{``        ``int` `arr[] = {``2``, ``13``, ``1``, ``19``, ``7``};``        ``int` `n = arr.length;``        ``int` `k = ``3``;``        ``System.out.println(xorGivenSetBits(arr, n, k));``    ``}``}`` ` `// This code contributed by Rajput-Ji`

## Python3

 `# Python 3 program to find Xor of all ``# elements with set bits equal to K`` ` `# Function to find Xor of desired elements``def` `xorGivenSetBits(arr, n, k):``     ` `    ``# Initialize vector``    ``v ``=` `[]``    ``for` `i ``in` `range``(``0``, n, ``1``):``        ``if` `(``bin``(arr[i]).count(``'1'``) ``=``=` `k):``             ` `            ``# push required elements``            ``v.append(arr[i])``         ` `    ``# Initialize result with first ``    ``# element of vector``    ``result ``=` `v[``0``]`` ` `    ``for` `i ``in` `range``(``1``, ``len``(v), ``1``):``        ``result ``=` `result ^ v[i]`` ` `    ``return` `result`` ` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``2``, ``13``, ``1``, ``19``, ``7``]``    ``n ``=` `len``(arr)``    ``k ``=` `3`` ` `    ``print``(xorGivenSetBits(arr, n, k))`` ` `# This code is contributed by``# Surendra_Gangwar`

## C#

 `// C# program to find Xor``// of all elements with set bits``// equal to K``using` `System;``using` `System.Collections;``using` `System.Linq;`` ` `class` `GFG``{``     ` `// Function to find Xor``// of desired elements``static` `int` `xorGivenSetBits(``int` `[]arr, ``int` `n, ``int` `k)``{``    ``// Initialize vector``    ``ArrayList v=``new` `ArrayList();`` ` `    ``for` `(``int` `i = 0; i < n; i++) ``    ``{``        ``if` `(Convert.ToString(arr[i], 2).Count(c => c == ``'1'``) == k) ``        ``{``            ``// push required elements``            ``v.Add(arr[i]);``        ``}``    ``}`` ` `    ``// Initialize result with first element of vector``    ``int` `result = (``int``)v;`` ` `    ``for` `(``int` `i = 1; i < v.Count; i++)``        ``result = result ^ (``int``)v[i];`` ` `    ``return` `result;``}`` ` `// Driver code``static` `void` `Main()``{``    ``int` `[]arr = { 2, 13, 1, 19, 7 };``    ``int` `n = arr.Length;``    ``int` `k = 3;`` ` `    ``Console.WriteLine(xorGivenSetBits(arr, n, k));``}``}`` ` `// This code is contributed by mits`
Output:
```25
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
{"ft_lang_label":"__label__en","ft_lang_prob":0.5035639,"math_prob":0.98060507,"size":3761,"snap":"2021-04-2021-17","text_gpt3_token_len":1223,"char_repetition_ratio":0.13734363,"word_repetition_ratio":0.2620321,"special_character_ratio":0.3589471,"punctuation_ratio":0.18007663,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.999481,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-04-16T07:15:58Z\",\"WARC-Record-ID\":\"<urn:uuid:d98b67cf-e902-43e5-ad4b-ed675701023d>\",\"Content-Length\":\"116721\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:d23c85e7-062a-48e5-bd62-26f4ade31559>\",\"WARC-Concurrent-To\":\"<urn:uuid:6550b454-c508-4653-a502-b8cacb62c734>\",\"WARC-IP-Address\":\"23.207.202.207\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/xor-of-all-elements-of-array-with-set-bits-equal-to-k/?ref=rp\",\"WARC-Payload-Digest\":\"sha1:33SYVQ2ICZIMIHTISVQWWNFFOODIOMBS\",\"WARC-Block-Digest\":\"sha1:SGJKDEHJSLKJSISDK6BHMIN2BTMJBDOR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-17/CC-MAIN-2021-17_segments_1618038088731.42_warc_CC-MAIN-20210416065116-20210416095116-00568.warc.gz\"}"}