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++
#include <bits/stdc++.h>
using namespace std;
int minVal( int a, int b)
{
int setBits = 0, res = 0;
setBits = __builtin_popcount(b);
stack< short int > s;
while (a > 0) {
s.push(a % 2);
a = a / 2;
}
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();
}
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();
while (setBits > 0) {
res += 1 << n;
n++;
setBits--;
}
return res;
}
int main()
{
int a = 3, b = 5;
cout << minVal(a, b);
return 0;
}
|
Java
public class GFG {
static int countSetBits( int n)
{
int count = 0 ;
while (n > 0 ) {
n = (n & (n - 1 ));
count++;
}
return count;
}
static int minValue( int a, int b)
{
int setBits = countSetBits(b);
int ans = 0 ;
for ( int i = 30 ; i >= 0 ; i--) {
int mask = ( 1 << i);
if ((mask & a) > 0 && setBits > 0 ) {
ans = ans | mask;
setBits--;
}
}
int i = 0 ;
while (setBits > 0 ) {
int mask = ( 1 << i);
if ((mask & ans) == 0 ) {
ans = ans | mask;
setBits--;
}
i++;
}
return ans;
}
public static void main(String[] args)
{
int a = 3 , b = 5 ;
System.out.println(minValue(a, b));
}
}
|
Python3
def minVal(a, b):
setBits = bin (b).count( '1' )
ans = 0
for i in range ( 30 , - 1 , - 1 ):
mask = ( 1 << i)
s = (a & mask)
if (s and setBits > 0 ):
ans | = ( 1 << i)
setBits - = 1
i = 0
while (setBits > 0 ):
mask = ( 1 << i)
if (ans & mask) = = 0 :
ans | = ( 1 << i)
setBits - = 1
i + = 1
return ans
if __name__ = = "__main__" :
a = 3
b = 5
print (minVal(a, b))
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
static int minVal( int a, int b)
{
int setBits = countSetBits(b);
int ans = 0;
for ( int i = 30; i >= 0; i--) {
int mask = 1 << i;
if ((a & mask) > 0 && setBits > 0) {
ans |= (1 << i);
setBits--;
}
}
int j = 0;
while (setBits > 0) {
int mask = (1 << j);
if ((mask & ans) == 0) {
ans = ans | mask;
setBits--;
}
j++;
}
return ans;
}
public static void Main()
{
int a = 3, b = 5;
Console.Write(minVal(a, b));
}
}
|
Javascript
<script>
function countSetBits(n) {
let count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
function minVal(a, b)
{
let setBits = countSetBits(b);
let ans = 0;
for (let i = 30; i >= 0; i--) {
let mask = 1 << i;
if ((a & mask) > 0 && setBits > 0) {
ans |= (1 << i);
setBits--;
}
}
return ans;
}
let a = 3, b = 5;
document.write(minVal(a, b));
</script>
|
Time Complexity: O(log(N))
Auxiliary Space: O(log(N))
2. Space efficient approach
By bit manipulation theory the Xor of two values will be minimised if they have same bits. By using this theory we will be dividing this problem into 3 parts as follows :
One is if the set bits of A and B are equal. Second is if the set bits of A are greater than B. Third is if the set bits of B are greater than A. If the set bits are equal then we will return A itself. If it falls under second case then we will remove the difference number of lower bits from A. If it falls under the third case then we will add the lower bits of A if the bit is not set in A.
Complexity
Time Complexity we need to iterate to all the bits present in A and B. The maximum number of bits are 30. so the complexity is O(log(max(A,B))).
Space Complexity We need to just iterate over the 30 bits and store the answer so the complexity is O(1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minVal( int a, int b)
{
int setb = __builtin_popcount(b);
int seta = __builtin_popcount(a);
int ans = 0;
for ( int i = 0; i <= 31; i++) {
int mask = 1 << i;
int set = a & mask;
if (set == 0 && setb > seta) {
ans |= (mask);
setb--;
}
else if (set && seta > setb)
seta--;
else
ans |= set;
}
return ans;
}
int main()
{
int a = 7, b = 12;
cout << minVal(a, b);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int NumberOfSetBits( int i)
{
i = i - ((i >> 1 ) & 0x55555555 );
i = (i & 0x33333333 ) + ((i >> 2 ) & 0x33333333 );
return (((i + (i >> 4 )) & 0x0F0F0F0F ) * 0x01010101 )
>> 24 ;
}
static int minVal( int a, int b)
{
int seta = NumberOfSetBits(a);
int setb = NumberOfSetBits(b);
int ans = 0 ;
for (var i = 0 ; i < 32 ; i++) {
int mask = 1 << i;
int set1 = a & mask;
if ((set1 == 0 ) && (setb > seta)) {
ans |= (mask);
setb -= 1 ;
}
else if ((set1 != 0 ) && (seta > setb))
seta -= 1 ;
else
ans |= set1;
}
return ans;
}
public static void main(String[] args)
{
int a = 7 ;
int b = 12 ;
System.out.println(minVal(a, b));
}
}
|
Python3
def minVal(a, b):
setb = bin (b)[ 2 :].count( '1' )
seta = bin (a)[ 2 :].count( '1' )
ans = 0
for i in range ( 0 , 32 ):
mask = 1 << i
set = a & mask
if ( set = = 0 and setb > seta):
ans | = (mask)
setb - = 1
elif ( set and seta > setb):
seta - = 1
else :
ans | = set
return ans
if __name__ = = "__main__" :
a = 7
b = 12
print (minVal(a, b))
|
Javascript
function minVal(a, b)
{
let setb = ((b.toString(2)).match(/1/g) || []).length;
let seta = ((a.toString(2)).match(/1/g) || []).length;
let ans = 0
for ( var i = 0; i < 32; i++)
{
let mask = 1 << i
let set1 = a & mask
if (set1 == 0 && setb > seta)
{
ans |= (mask)
setb -= 1
}
else if (set1 && seta > setb)
seta -= 1
else
ans |= set1
}
return ans
}
let a = 7
let b = 12
console.log(minVal(a, b))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int NumberOfSetBits( int i)
{
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101)
>> 24;
}
static int minVal( int a, int b)
{
int seta = NumberOfSetBits(a);
int setb = NumberOfSetBits(b);
int ans = 0;
for ( var i = 0; i < 32; i++) {
int mask = 1 << i;
int set1 = a & mask;
if ((set1 == 0) && (setb > seta)) {
ans |= (mask);
setb -= 1;
}
else if ((set1 != 0) && (seta > setb))
seta -= 1;
else
ans |= set1;
}
return ans;
}
public static void Main( string [] args)
{
int a = 7;
int b = 12;
Console.WriteLine(minVal(a, b));
}
}
|
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
13 Oct, 2022
Like Article
Save Article