Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum Bitwise XOR operations to make any two array elements equal
Next article icon

XOR of all elements of array with set bits equal to K

Last Updated : 31 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Approach: 

  1. Initialize an empty vector.
  2. Traverse the array from 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 <bits/stdc++.h>
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[0];
 
    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[0]);
    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<Integer> 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[0];
 
    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
 
 

Javascript




<script>
 
// Javascript program to find Xor
// of all elements with set bits
// equal to K
 
// Function to find Xor
// of desired elements
function xorGivenSetBits(arr, n, k)
{
    // Initialize vector
    let v = [];
 
    for (let i = 0; i < n; i++) {
        if (bitcount(arr[i]) == k) {
            // push required elements
            v.push(arr[i]);
        }
    }
 
    // Initialize result with first
    // element of vector
    let result = v[0];
 
    for (let i = 1; i < v.length; i++)
        result = result ^ v[i];
 
    return result;
}
 
function bitcount(n)
{
  var count = 0;
  while (n)
  {
    count += n & 1;
    n >>= 1;
  }
  return count;
}
 
// Driver code
    let arr = [ 2, 13, 1, 19, 7 ];
    let n = arr.length;
    let k = 3;
 
    document.write(xorGivenSetBits(arr, n, k));
 
</script>
 
 
Output
25


Next Article
Minimum Bitwise XOR operations to make any two array elements equal

S

Shashank_Sharma
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Bitwise-XOR
  • setBitCount
Practice Tags :
  • Arrays
  • Bit Magic

Similar Reads

  • Sorting array elements with set bits equal to K
    Given an array of integers and a number [Tex]K [/Tex]. The task is to sort only those elements of the array whose total set bits are equal to K. Sorting must be done at their relative positions only without affecting any other elements.Examples: Input : arr[] = {32, 1, 9, 4, 64, 2}, K = 1 Output : 1
    6 min read
  • Count of even and odd set bit with array element after XOR with K
    Given an array arr[] and a number K. The task is to find the count of the element having odd and even number of the set-bit after taking XOR of K with every element of the given arr[].Examples: Input: arr[] = {4, 2, 15, 9, 8, 8}, K = 3 Output: Even = 2, Odd = 4 Explanation: The binary representation
    9 min read
  • Minimum Bitwise XOR operations to make any two array elements equal
    Given an array arr[] of integers of size N and an integer K. One can perform the Bitwise XOR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make a
    9 min read
  • Sum of Bitwise XOR of elements of an array with all elements of another array
    Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[]. Examples: Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}Output: 7 34 11Explanation:For Q[0] ( = 3): Sum = 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.For
    9 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Minimum Bitwise AND operations to make any two array elements equal
    Given an array of integers of size 'n' and an integer 'k', We can perform the Bitwise AND operation between any array element and 'k' any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make an
    10 min read
  • Count sub-arrays which have elements less than or equal to X
    Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4,
    15 min read
  • Sum of array elements whose count of set bits are unique
    Given an array arr[] consisting of N positive integers, the task is to find the sum of all array elements having a distinct count of set bits in the array. Examples: Input: arr[] = {8, 3, 7, 5, 3}Output: 15Explanation:The count of set bits in each array of elements is: arr[0] = 8 = (1000)2, has 1 se
    7 min read
  • Minimize Bitwise XOR of array elements with 1 required to make sum of array at least K
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to count minimum Bitwise XOR of array elements with 1 required such that the sum of the array is at least K. Examples: Input: arr[] = {0, 1, 1, 0, 1}, K = 4Output: 1Explanation: Performing Bitwise XOR of arr
    6 min read
  • Find element with the maximum set bits in an array
    Given an array arr[]. The task is to find an element from arr[] which has the maximum count of set bits.Examples: Input: arr[] = {10, 100, 1000, 10000} Output: 1000 Binary(10) = 1010 (2 set bits) Binary(100) = 1100100 (3 set bits) Binary(1000) = 1111101000 (6 set bits) Binary(10000) = 10011100010000
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences