c++ - What is the purpose of & in (a & 1) -


this question has answer here:

i trying solve problem in codefights, after browsing net, found solution.but not clear how works.

    * (a & 1) ^ b * !(b & 1) ^ !!(((a ^ b) + 1) & 2) 

a single & bitwise and, means result bits set on both left , right side of operator.

as example 15 & 7 or represented in binary:

1111 & 0111 

the bitwise , result in number common bits set:

1111 & 0111 = 0111 

when make (a & 1) testing whether least significant bit (lsb) set, since performing test this:

a & 00000001 

if a had bitwise value: 00000110 result 0, since there no common bits set, if a had bitwise value: 00000111 result 1 since lsb set on a.

this used different situations, if lsb set know number odd, test whether number odd or not (1, 3, 5, 7, ...).

looking @ first part of solution: a * (a & 1) multiplying a value of (0 or 1 remember), 1 if a odd, , 0 if even.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -