![]() |
VOOZH | about |
Given a positive integer N, the task is to find the two smallest integers A and B such that the Bitwise XOR of A and B is N and the difference between A and B is minimum.
Examples:
Input: N = 26
Output: 10 16
Explanation:
The Bitwise XOR of 10 and 16 is 26 and the difference between them is minimum.Input: N = 1
Output: 0 1
Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs of the numbers over the range [0, N] and print that pair of numbers whose Bitwise XOR is the given number N and both the numbers are smallest.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can also be optimized based on the following observations:
From the above observations, the minimum value of A and B satisfying the given criteria is to split the given number N around its Most Significant Bit(MSB).
Below is the implementation of the above approach:
10 16
Time Complexity: O(1)
Auxiliary Space: O(1)