Given two integers A and B. The task is to choose an integer X such that (A xor X) + (B xor X) is the minimum possible.
Input: A = 2, B = 3
Output: X = 2, Sum = 1
Input: A = 7, B = 8
Output: X = 0, Sum = 15
A simple solution is to generate all possible sum by taking xor of A and B with all possible values of X ≤ min(A, B). To generate all possible sums it would take O(N) time where N = min(A, B).
An efficient solution is based on the fact that the number X will contain the set bits only at that index where both A and B contain a set bit such that after xor operation with X that bit will be unset. This would take only O(Log N) time.
Other cases: If at a particular index one or both the numbers contain 0 (unset bit) and the number X contains 1 (set bit) then 0 will be set after xor with X in A and B then the sum couldn’t be minimized.
Below is the implementation of the above approach:
X = 2, Sum = 1
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.
- Choose an integer K such that maximum of the xor values of K with all Array elements is minimized
- Find a point such that sum of the Manhattan distances is minimized
- Delete odd and even numbers at alternate step such that sum of remaining elements is minimized
- Partition the array into two odd length groups with minimized absolute difference between their median
- Divide a sorted array in K parts with sum of difference of max and min minimized in each part
- Select K elements from an array whose maximum value is minimized
- Choose points from two ranges such that no point lies in both the ranges
- Ways to choose balls such that at least one ball is chosen
- Choose two elements from the given array such that their sum is not present in any of the arrays
- Number of ways to choose a pair containing an even and an odd number from 1 to N
- Find if it is possible to choose subarray that it contains exactly K even integers
- Puzzle | Choose the game of Rolling Dice
- Given a set, find XOR of the XOR's of all subsets.
- Find XOR of two number without using XOR operator
- Count minimum bits to flip such that XOR of A and B equal to C
- Count all Quadruples from four arrays such that their XOR equals to 'x'
- Find smallest number n such that n XOR n+1 equals to given k.
- Find number of pairs in an array such that their XOR is 0
- Count ordered pairs of positive numbers such that their sum is S and XOR is K
- Minimum value of N such that xor from 1 to N is equal to K
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.