Well, you can use the XOR of l and r to find the answer.
Suppose, l=4 and r = 6.
l = 100, r = 110 (binary equivalents of these numbers)
l⊕r = 010
What this means is, the maximum value you are looking for will definitely have its first bit(MSB) as zero. (Think about it, is it even possible for your maximum value to have a 1 in the first bit instead? If it was 01010 and 00101, the xor would have been = 01111 i.e. the max. value between 01010 and 00101 will definitely have a 1 in their second bit from left, it is not possible to get a 1 before the second bit from left i.e. in the first bit from the left)
So, you are left with the remaining 2 bits to find the maximum. We know, that the maximum possible value when we have n bits with us is = 2n−1, therefore the answer in this case will be 22 -1 = 4-1 = 3.
From the example above, we can make a general algorithm for this.
Step 1. num = number of bits required to represent max(l , r)
Step 2. res = l ⊕ r
Step 3. pos = Position of the first-bit that is set from the left in res (0-based indexing)
Step 4. n = num - pos
Step 5. ans = 2n−1
Time complexity = O(n)