Given a number X and integer N, give the max value for (X&i) 0<=i<=N. Example: X = 103, N = 50 ans = 44
2026-03-26 16:10:24.1774541424
Max value of bitwise AND over a given range
227 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail At
1
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$):
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$.
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.