I cant understand the logic, please explain
The logic is simple. We have to first determine the number of bits in the maximum xor value. The first while loop does that. The second loop just uses the bit size determined in the first loop and sets all bits to 1 and determines the number.
The reason why the first loop gives the size of maximum xor value can be explained by an example.
For ex if you take l = 3 (011) and r = 15 (1111) x will be 1100.
Then pos will be 4 which is the maximum number of bits in the xor value. So the second loop returns 1111. Once the bit size is determined it is easy to see that it is a simple step to choose some values in the range which will return 1 for all bit positions lesser than the most significant bit which is pos.
If l is 3 and r is 6 (110), then x is 101 and pos will be 3 bits. The value returned is 111.