Max value of bitwise AND over a given range

227 Views Asked by At

Given a number X and integer N, give the max value for (X&i) 0<=i<=N. Example: X = 103, N = 50 ans = 44

1

There are 1 best solutions below

0
On BEST ANSWER

If $N \geq X$, the simply return $X$.

If $N \leq X$, then start from the most-significant bit of $N$ (i.e. the left-most place value with a $1$). We will denote the bit we are examining as place value $b$, and also keep a value $A$ (which will be our answer). $A$ is initialized to zero. Then do the following loop (again, we start at the most significant bit of $N$):

  1. If the $b$ place value of $X$ is $x$ and the $b$ place value of $N$ is also $x$, then set the $b$ place value of $A$ to be $x$.

  2. If the $b$ place value of $X$ is $0$ and the $b$ place value of $N$ is $1$, then set the remaining (lesser significant bits) of $A$ to match the respective bits in $X$, and exit the loop.

The answer (i.e. the maximum value of $X ~ \& ~ i$) will be $A$ at the end.