-5

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.

Rajeev
  • 5
  • 3

1 Answers1

2

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.

Shubhzgang
  • 322
  • 2
  • 9
  • But will it be smallest ? – Rajeev May 07 '20 at 06:55
  • Other than the answer above, AND-ing `11`, `14` and `15` with `N` would give you max value of `10`. Since we are not setting the bits on the position where `N` has a `0`, we are not increasing the value of answer unnecessarily. Like we can put a `1` at second step also to get the max bitwise value AND with N, but that is going to be AND-ed (if that is word?) with the `0` in `N`. We are avoiding that. – Shubhzgang May 07 '20 at 07:07