Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal - GeeksforGeeks

01 Mar, 2022
Given two integers A and B, the task is to find an integer X such that (X XOR A) is minimum possible and the count of set bit in X is equal to the count of set bits in B.Examples:  
Input: A = 3, B = 5 Output: 3 Binary(A) = Binary(3) = 011 Binary(B) = Binary(5) = 101 The XOR will be minimum when M = 3 i.e. (3 XOR 3) = 0 and the number of set bits in 3 is equal to the number of set bits in 5.Input: A = 7, B = 12 Output: 6  
 
Approach: It is known that the xor of an element with itself is 0. So, try to generate M’s binary representation as close to A as possible. Traverse from the most significant bit in A to the least significant bit and if a bit is set at the current position then it also needs to be set in the required number in order to minimize the XOR but the number of bits set has to be equal to the number of set bits in B. So, when the count of set bits in the required number has reached the count of set bits in B then the rest of the bits have to be 0.
 It can also be possible that the number of set bits in B is more than the number of set bits in A, In this case, start filling the unset bits to set bits from the least significant bit to the most significant bit.
 If the number of set bits is still not equal to B then add the remaining number of set bits to the left of the most significant bit in order to make set bits of M equal to the set bits of B.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the value x// such that (x XOR a) is minimum// and the number of set bits in x// is equal to the number// of set bits in bint minVal(int a, int b) {                 int setBits=0,res=0;                   //To count number of set bits in b        setBits= __builtin_popcount(b);                 //creating binary representation of a in stack s        stack<short int> s;        while(a>0)        {            s.push(a%2);            a=a/2;        }                  // Decrease the count of setBits        // as in the required number set bits has to be        // equal to the count of set bits in b        //Creating nearest possible number in m in binary form.        //Using vector as the number in binary for can be large.        vector<short int> m;                    while(!s.empty())        {            if(s.top()==1 && setBits>0)            {                m.push_back(1);                setBits--;            }            else            {                m.push_back(0);            }            s.pop();        }                 //Filling the unset bits from the least significant bit to the most significant bit        //if the setBits are not equal to zero        for(int i=m.size()-1;i>=0 && setBits>0;i--)        {            if(m[i]==0)            {                m[i]=1;                setBits--;            }        }                          int mask;        for(int i=m.size()-1;i>=0;i--)        {            mask=1<<(m.size()-i-1);                         res+=m[i]*mask;        }        int n=m.size();                 //if the number of setBits is still not equal to zero        //dd the remaining number of set bits to the left of the most significant bit        //in order to make set bits of m equal to the set bits of B.                 while(setBits>0)        {            res+=1<<n;            n++;            setBits--;        }                 return res;    } // Driver codeint main(){    int a = 3, b = 5;     cout << minVal(a, b);     return 0;}
// Java implementation of the approachclass GFG{    // Function to get no of set    // bits in binary representation    // of positive integer n    static int countSetBits(int n)    {        int count = 0;        while (n > 0)        {            count += n & 1;            n >>= 1;        }        return count;    } // Function to return the value x// such that (x XOR a) is minimum// and the number of set bits in x// is equal to the number// of set bits in bstatic int minVal(int a, int b){    // Count of set-bits in bit    int setBits = countSetBits(b);    int ans = 0;     for (int i = 30; i >= 0; i--)    {        int mask = 1 << i;                 // If i'th bit is set also set the        // same bit in the required number        if ((a & mask) > 0 && setBits > 0)        {            ans |= (1 << i);                         // Decrease the count of setbits            // in b as the count of set bits            // in the required number has to be            // equal to the count of set bits in b            setBits--;        }    }    return ans;} // Driver Codepublic static void main(String[] args){    int a = 3, b = 5;     System.out.println(minVal(a, b));}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Function to return the value x# such that (x XOR a) is minimum# and the number of set bits in x# is equal to the number# of set bits in bdef minVal(a, b) :     # Count of set-bits in bit    setBits = bin(b).count('1');    ans = 0;     for i in range(30, -1, -1) :        mask = (1 << i);        s = (a & mask);         # If i'th bit is set also set the        # same bit in the required number        if (s and setBits > 0) :            ans |= (1 << i);             # Decrease the count of setbits            # in b as the count of set bits            # in the required number has to be            # equal to the count of set bits in b            setBits -= 1;     return ans; # Driver codeif __name__ == "__main__" :     a = 3; b = 5;     print(minVal(a, b)); # This code is contributed by kanugargng
// C# implementation of the approachusing System; class GFG{    // Function to get no of set    // bits in binary representation    // of positive integer n    static int countSetBits(int n)    {        int count = 0;        while (n > 0)        {            count += n & 1;            n >>= 1;        }        return count;    } // Function to return the value x// such that (x XOR a) is minimum// and the number of set bits in x// is equal to the number// of set bits in bstatic int minVal(int a, int b){    // Count of set-bits in bit    int setBits = countSetBits(b);    int ans = 0;     for (int i = 30; i >= 0; i--)    {        int mask = 1 << i;                 // If i'th bit is set also set the        // same bit in the required number        if ((a & mask) > 0 && setBits > 0)        {                         ans |= (1 << i);                         // Decrease the count of setbits            // in b as the count of set bits            // in the required number has to be            // equal to the count of set bits in b            setBits--;        }    }     return ans;} // Driver Codepublic static void Main(){    int a = 3, b = 5;     Console.Write(minVal(a, b));}} // This code is contributed by Mohit kumar 29
<script>// Javascript implementation of the approach // Function to get no of set// bits in binary representation// of positive integer nfunction countSetBits(n) {    let count = 0;    while (n > 0) {        count += n & 1;        n >>= 1;    }    return count;} // Function to return the value x// such that (x XOR a) is minimum// and the number of set bits in x// is equal to the number// of set bits in bfunction minVal(a, b){     // Count of set-bits in bit    let setBits = countSetBits(b);    let ans = 0;     for (let i = 30; i >= 0; i--) {        let mask = 1 << i;         // If i'th bit is set also set the        // same bit in the required number        if ((a & mask) > 0 && setBits > 0) {             ans |= (1 << i);             // Decrease the count of setbits            // in b as the count of set bits            // in the required number has to be            // equal to the count of set bits in b            setBits--;        }    }     return ans;} // Driver Codelet a = 3, b = 5; document.write(minVal(a, b)); // This code is contributed by gfgking.</script>
3
 
Time Complexity: O(log(N))
Auxiliary Space: O(log(N))
kanugargng
mohit kumar 29
Rajput-Ji
gfgking
sarthikmehtasm
subhammahato348
Bitwise-XOR
setBitCount
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Program to find whether a given number is power of 2
Binary representation of a given number
Bit Fields in C
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers