Maximizing XOR

que-1 how did this logic worked out i know we should do xor of least set bits number and most having unset bit number so that they differ each other and gives large output number but i seen the code i am not getting any clue how it worked.
int value = L ^ r;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
return value;

que-2 how to find the maximum of an array using bitwise xor.

https://www.hackerrank.com/challenges/maximizing-xor/submissions/code/195472529

CODE

any one please rply i been struck in this problem for a long time.

hi, in this problem, the limits are up to 1000, that means that you can brute force it.

in c++, for xor operation (a xor b), you can use “a^b” or “a xor b”.

xor works in this form:

  • 0 xor 0 is 0
  • 0 xor 1 is 1
  • 1 xor 0 is 1
  • 1 xor 1 is 0

every integer is like a bitset, in binary form, int with 32 bits, long long with 64 bits.

so in “a xor b” for every bit is applyed the operation. the result is the number that represents that bitset.

example:

11 xor 12:

11 = 00…1011
12 = 00…1100

11 xor 12 = 00…0111

00…0111 = 7, so 11 xor 12 is 7.

i don’t know if this helped, but if not, you can ask me.

1 Like

Thank you for your explanation but still i was not understand what this part of code does
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
return value;

that’s the or operation, used with the right shift operator:

  • 0 or 0 is 0
  • 0 or 1 is 1
  • 1 or 0 is 1
  • 1 or 1 is 1

the same way as the xor operation, but with the above rules.

the right shift operator, as the name says, shift the binary form of the number n, x times to the right ( n >> x )

example:

  • 9 >> 2.

9 = 00…1001, so 9 >> 2 is 00…10, the 2 right numbers are “deleted”.

so 9 >> 2, is 2 (00…10).

1 Like

thanks man you cleared it but still one small doubt i have
lets say i have an interger 10=(binary representation)0000000001010 so if i right shift the bits to 4 then the binary representation will become A=0000000000000 right or B=101000000000 this one . The doubt is which one it will become after shifting A OR B.:slight_smile: little confused

it will become option A, zero, the most-right bit is erased, and a 0-bit is added to the left

1 Like

Thank you :slight_smile: