Given a positive integer N , and a range of positive integers from L to R . Find the smallest positive integer in the range having Maximum Bitwise AND value with N.
NOTE: N needn't to be necessarily lie in the range L to R.
Given a positive integer N , and a range of positive integers from L to R . Find the smallest positive integer in the range having Maximum Bitwise AND value with N.
NOTE: N needn't to be necessarily lie in the range L to R.
Lets assume the answer for now to be zero 0
. Take the binary representation of N. Go from Most significant bit (MSB) to Least Significant bit (LSB), one by one. If you get a 0
, skip. If you get a 1
, bitwise OR it with the answer (keeping 1
at the same position) and see if answer is in the range from L to R. If Answer
is less than equal to R
(assuming the R
to be inclusive), keep the bit as 1
(even if it is less than L
). If Answer
is greater than R
, revert the bit to 0
and go to next bit in N
.
Example 1:
N
= 10 decimal, 1010
binary.
L
= 5.
R
= 15.
Answer
= 0.
We start from the MSB 1
of N
.
Answer
OR 1000
= 1000 binary is between L
and R
. We keep it and move to next bit in N
.
Next bit is 0
. We do nothing and go to next bit.
Next bit is 1
. Answer
OR 0010
= 1010
, which is between L
and R
. We keep it and go ahead.
Next bit is 0
. We do nothing. We are at the end of N
. We have our answer.
Answer
= 1010
.
Example 2: N = 45 (101101
), L = 32, R = 36.
Answer
OR 100000
= 100000
which is 32, between L
and R
. We keep it as 1
and proceed.
Answer
OR 1000
= 101000
which is 40. Greater than R
. We revert answer to 100000
and proceed.
Answer
OR 100
= 100100
which is 36. Which is R
. Another optimization: we can stop here since OR-ing anything with Answer
will now increase its value beyond R
.
Some more optimizations can be done, like if N
and R
are equal, R
should be the answer.
In some cases, the answer might come as 0
(Ex. N
= 45, L
= 16, R
= 16). Can take L
as the answer depending on the specification of the question.