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.
Input: A = 3, B = 5
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
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.
Below is the implementation of the above approach:
Time Complexity: O(log(N))
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.
- Count minimum bits to flip such that XOR of A and B equal to C
- Check if bits of a number has count of consecutive set bits in increasing order
- XOR of all elements of array with set bits equal to K
- Count pairs in an array such that both elements has equal set bits
- Count positions in Binary Matrix having equal count of set bits in corresponding row and column
- Count of even set bits between XOR of two arrays
- Count set bits in Bitwise XOR of all adjacent elements upto N
- Minimum value of N such that xor from 1 to N is equal to K
- Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
- Count pairs of elements such that number of set bits in their AND is B[i]
- Choose X such that (A xor X) + (B xor X) is minimized
- Count pairs of elements such that number of set bits in their OR is B[i]
- Given a set, find XOR of the XOR's of all subsets.
- Find a number such that maximum in array is minimum possible after XOR
- Print numbers having first and last bits as the only set bits
- Find XOR of two number without using XOR operator
- Minimum integer with at most K bits set such that their bitwise AND with N is maximum
- Toggle bits of a number except first and last bits
- Number of subarrays such that XOR of one half is equal to the other
- Minimum bit flips such that every K consecutive bits contain at least one set bit
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.