Minimum value of K such that Bitwise XOR of K with all array elements is minimum

By | January 30, 2023

Given an array of N elements, the task is to find the minimum value of K such that Bitwise XOR of K with all array elements is minimum

Input: arr[] 16 12 20 18
Output: 16
Explanation: 16^16+12^16+20^16+18^16 =26 Minimum sum

Explanation:

  • Check every bit of the numbers and count number of one and zero
  • For minimum sum, we have to swap all the one’s bit to the zero
  • If the number of ones is greater than the number of zeros set the position to the one otherwise skip the set i.e mark zero

Java code implementation :

//Importing libraries
import java.io.*;

class Main {
    
    //Function to check minimumvalue  
    static void minimumvalue(int arr[]) {
        
        int ans = 0;
        
        //Iterate the loop till the limit of the integer
        for (int index = 0; index < 32; ++index) {
            
            int ones = 0;
            int zeros = 0;
            for (int index1 = 0; index1 < arr.length; ++index1) {
                
                //Check every element bit
                if ((arr[index1] & (1 << index)) != 0) {
                    ++ones;
                } else {
                    ++zeros;
                }
            }

            if (ones > zeros) {
                
                //Set the bit to the answer
                ans += (1 << index);
            }
        }
        
        //Print the answer
        System.out.println(ans);
    }
    
    public static void main(String[] args) {
        int arr[] = {
            15,
            12,
            13,
            17
        };
        
        minimumvalue(arr);
    }
}

Output:

13

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.