a & b
is at leastk - 2
because:- If
k - 2
is even, the least significant bit (LSB) ofk - 2
is0
. Assigna = k - 2
. - If
k - 1
is even, LSB ofk - 1
is 0. Assigna = k - 1
. - Either way, LSB of
a + 1
is1
. Assignb = a + 1
. So,a & b == a
.
- If
a & b
can bek - 1
in the following case:- Given the constraints
a < b
anda & b < k
, fora & b == k - 1
to hold,a = k - 1
. - For
((k - 1) & b) === k - 1
to hold,b
is the same ask - 1
except one bit, which is positioned ata
's any bit of 0, is 1. - To be precise, the exception bit of
b
must be positioned ata
's LSB of0
to minimize the chance ofb
exceedingn
. Suchb
is(k - 1) | k
.
- Given the constraints
- In conclusion,
a & b = k - 1
whena = k - 1
andb = ((k - 1) | k) <= n
. Otherwise,a & b = k - 2
.
A naive implementation of the above logic is:
function getMaxLessThanK(n, k) {
let a = k - 1;
let b = (k - 1) | k;
if (n < b) {
a = k - 2;
b = a + 1;
}
return a & b;
}
The shorter implementation is:
function getMaxLessThanK(n, k) {
return ((k - 1) | k) <= n ? (k - 1) : (k - 2);
}