https://www.codechef.com/problems/DRAGNXOR
Maximum Xor of two bit patterns | Letuscode
Given two numbers
For example assume
Let us look at another example
This problem was originally appeared on Codechef. The problem has 3 inputs N (number of bits), A, B. How many 1s are possible in the result number?
Since
How should we arrange these bits to get the maximum value? All 1s should be pushed to left (Most significant bits). So the result will be of the form 1111…00
public static void main(String []args) {
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
while( t-- > 0 ) {
int nBits = reader.nextInt();
int a = reader.nextInt();
int b = reader.nextInt();
System.out.println(maxXor(nBits, a, b));
}
}
private static int maxXor(int n, int a, int b) {
int aBits = Integer.bitCount(a);
int bBits = Integer.bitCount(b);
int ones = Math.min(aBits, n-bBits) + Math.min(bBits, n-aBits);
return ((1 << ones)-1) << (n-ones);
}
Read full article from Maximum Xor of two bit patterns | Letuscode
Maximum Xor of two bit patterns | Letuscode
Given two numbers
A, B
, What is the maximum value of A' XOR B'
, where A', B'
are obtained by permuting the binary representations of A, B
respectively.For example assume
A = 3, B = 1
and they are represented in 4 bits. A = 0011, B = 0001
in binary. Suppose A' = 1100, B' = 0010
, then we get the A' ^ B' = 1110 = 13
. So 13 is the answer. For no other values of A', B', the XOR will be maximum.Let us look at another example
A = 3, B = 7
, again represented using 4 bits. A' = 0011, B' = 1101
and A' ^ B' = 0011 ^ 1101 = 1110 = 14
. So 14 is the answer.This problem was originally appeared on Codechef. The problem has 3 inputs N (number of bits), A, B. How many 1s are possible in the result number?
Since
1^0 = 1 and 0^1 = 1
, to get a 1 in the final result, We should have a- 1 bit in A, and 0 bit in B or
- 0 bit in A, and 1 bit in B
How should we arrange these bits to get the maximum value? All 1s should be pushed to left (Most significant bits). So the result will be of the form 1111…00
public static void main(String []args) {
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
while( t-- > 0 ) {
int nBits = reader.nextInt();
int a = reader.nextInt();
int b = reader.nextInt();
System.out.println(maxXor(nBits, a, b));
}
}
private static int maxXor(int n, int a, int b) {
int aBits = Integer.bitCount(a);
int bBits = Integer.bitCount(b);
int ones = Math.min(aBits, n-bBits) + Math.min(bBits, n-aBits);
return ((1 << ones)-1) << (n-ones);
}
Read full article from Maximum Xor of two bit patterns | Letuscode