I think your code is perfect till line 26. Now, i stores the position of the highest set bit of r, considering that the LSB is at position 0. The don’t quite understand the logic that follows afterwards. You are only left with 2 simple steps:
x is the i-th bit of l and y is the i-th bit of r. While x equals y, you OR either of the two with a and decrement i. Do so till either i reaches 0 or x does not equal y.
Now that we have injected the longest identical prefix of l and r into a, all that’s left is to OR a string of set bits of length i + 1 with a.
I think the editorial has done a good job explaining why this works. Hope this helps.
I got a massive hint about solving the problem by doing the problem thanks to the fourth test case. (Although I solved it in practice). This can be quite useful if the testcases supplied to us are “nice”.
I converted 1000000000123, 1000000123456, 1000000192511 to binary. Here I observed that the final answer in binary is as follows:
"111010001101010010100"“1111111111111111111”. That lead me to the pattern quickly that all common leading bits are to be retained and all bits that follow are to be set.
What is wrong to my solution. Anyone please do try to figure, we can also use long instead of BigInteger. This solution is first finding log of L and R, then accordingly generated two nums (2^n - 1) will generate number with all bits set while 2^n will generate number with only one (MSB) bit set. then ORing is done. it is running for successfully for first three cases as explained in problem example but not for the last one.