a & bis at leastk - 2because:- If
k - 2is even, the least significant bit (LSB) ofk - 2is0. Assigna = k - 2. - If
k - 1is even, LSB ofk - 1is 0. Assigna = k - 1. - Either way, LSB of
a + 1is1. Assignb = a + 1. So,a & b == a.
- If
a & bcan bek - 1in the following case:- Given the constraints
a < banda & b < k, fora & b == k - 1to hold,a = k - 1. - For
((k - 1) & b) === k - 1to hold,bis the same ask - 1except one bit, which is positioned ata's any bit of 0, is 1. - To be precise, the exception bit of
bmust be positioned ata's LSB of0to minimize the chance ofbexceedingn. Suchbis(k - 1) | k.
- Given the constraints
- In conclusion,
a & b = k - 1whena = k - 1andb = ((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);
}