Given two integers A and B. The task is to choose an integer X such that (A xor X) + (B xor X) is 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 value 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 contains 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
- 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
- Choose points from two ranges such that no point lies in both the ranges
- Number of ways to choose a pair containing an even and an odd number from 1 to N
- Find number of factors of N when location of its two factors whose product is N is given
- Square free semiprimes in a given range using C++ STL
- Maximum XOR with given value in the path from root to given node in the tree
- Count number of pairs in array having sum divisible by K | SET 2
- Count number of pairs of lines intersecting at a Point
- Maximum number of region in which N non-parallel lines can divide a plane
- 21 Matchsticks Problem
- Minimum Possible sum of digits in a positive multiple of N
- Find the smallest positive number which can not be represented by given digits
- Find the average of k digits from the beginning and l digits from the end of the given number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.