-4

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)
Real73
  • 490
  • 4
  • 13
user3779015
  • 499
  • 1
  • 4
  • 19

2 Answers2

6

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.

Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50
-1

Here & is a Bitwise Operator(works on bits and perform bit-by-bit operation).For more details see this and this

Real73
  • 490
  • 4
  • 13
  • Please extract the relevant parts from the external links, so to not make the answer vulnerable to dead links :) – Tommy Andersen Nov 08 '16 at 11:31
  • @TommyAndersen How to do this? i can't.any help? – Real73 Nov 08 '16 at 12:19
  • Please see this link: http://stackoverflow.com/help/how-to-answer according to the Stack Overflow guide to writing good answers, links should be accompanied by relevant quotes from the link. For instance copy the text from the link that is relevant to the ops question and insert in connection with the link. This adds some context to the answer that will be helpful, even if the link should stop working. :) – Tommy Andersen Nov 08 '16 at 16:16