I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
I want to know about what is the use of that (index & 0x01) in the code?
if(((arr[index] >= 0) && (!(index & 0x01)))
|| ((arr[index] < 0) && (index & 0x01)))
{
outofplace = index;
}
A number is odd if and only if its last digit is odd, regardless of the base. So if we want to know the number's oddity, it's enough to check if the last bit is set.
index & 0x01
will be 1
if and only if index
is odd.
If we have to deduce a general rule, we can say that for any non-negative number x
,
x % y == (x & (y - 1))
provided that y
is a positive power of 2
.
This is a common hack in competitive coding. It is used because the competitive programmers think that bit-wise AND works faster than modulo.
In modern compilers, there is no performance difference at all. Read this thread.
There is no special reason in writing it as 0x01
instead of 1
. Both compile to give the same assembly! Almost everyone (who uses this hack),= uses 1
, because we have to type 3 characters extra in 0x01
. :P
Here in this case, index & 0x1
is equivalent to index % 2
which is simply a condition to check if the number is odd. (Array indexes in C++ are always positive, unless you are going out of bound.)
As the other answers pointed out, while this is a well known pattern (see also this Q&A about that mask), it can be considered a premature optimization.
I'd like to suggest the following alternative to the posted code, which I find more readable. Your mileage may vary.
// Give a meaningful name. constexpr auto is_odd = [] (auto x) -> bool { return x % 2; } // Use it to simplify the condition. if ( (arr[index] < 0) == is_odd(index) ) { // Do something }