Smallest pair of integers with minimum difference whose Bitwise XOR is N
Last Updated :
02 Aug, 2021
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:
- Consider the binary representation of any number is “1100011”, then the number can be split around their Most Significant Bit(MSB) as “1000000” and “100011” and the Bitwise XOR of these numbers is the given number.
- From the above splitting, it can be observed that the number formed by “1000000”(say A) and “100011”(say B) is minimum and their difference between them is minimum as the value formed by B with always be smaller and closest to A.
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:
C++
#include <bits/stdc++.h>
using namespace std;
void findAandB( int N)
{
int K = log2(N);
int B = (1 << K);
int A = B ^ N;
cout << A << ' ' << B;
}
int main()
{
int N = 26;
findAandB(N);
return 0;
}
|
Java
public class MyClass
{
static void findAandB( int N)
{
int K = ( int )(Math.log(N) / Math.log( 2 ));
int B = ( 1 << K);
int A = B ^ N;
System.out.println(A + " " + B);
}
public static void main(String args[]) {
int N = 26 ;
findAandB(N);
}
}
|
Python3
from math import log2
def findAandB(N):
K = int (log2(N))
B = ( 1 << K)
A = B ^ N
print (A, B)
if __name__ = = '__main__' :
N = 26
findAandB(N)
|
C#
using System;
class GFG{
static void findAandB( int N)
{
int K = ( int )(Math.Log(N) /
Math.Log(2));
int B = (1 << K);
int A = B ^ N;
Console.Write(A + " " + B);
}
public static void Main(String[] args)
{
int N = 26;
findAandB(N);
}
}
|
Javascript
<script>
function findAandB(N) {
let K = Math.log2(N);
let B = (1 << K);
let A = B ^ N;
document.write(A + ' ' + B);
}
let N = 26;
findAandB(N);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...