I am trying to solve a problem in codefights, after browsing the net, i found this solution.But i am not clear how it works.
a * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2)
I am trying to solve a problem in codefights, after browsing the net, i found this solution.But i am not clear how it works.
a * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2)
A single &
is a bitwise AND, which means that the result is the bits that are set on BOTH left and right side of the operator.
As an example 15 & 7
or as they are represented in binary:
1111
&
0111
The bitwise AND will result in the a number with the common bits set:
1111 & 0111 = 0111
When you make the (a & 1)
you are testing whether the least significant bit (lsb) is set, since you are performing a test like this:
a
&
00000001
If a
had the bitwise value: 00000110 then the result would be 0, since there are no common bits set, if a
had the bitwise value: 00000111 then the result would be 1 since the lsb is set on a.
This is used for different situations, if the lsb is set you know that the number is odd, so this test is really whether the number is odd or not (1, 3, 5, 7, ...).
Looking at the first part of your solution: a * (a & 1)
you are multiplying a
with the value of (0 or 1 remember), 1 if a
is odd, and 0 if it is even.
Here &
is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this