Namely, val = x ^ y;
and val &= val - 1;
__int64 dist = 0, val = x ^ y; // Count the number of set bits while(val) { ++dist; val &= val - 1; } return dist;
^ - bitwise exclusive OR (XOR)
a = 5; // 101 двоичное b = 3; // 011 двоичное c = ( a ^ b ); // c равно 110 двоичному ( 6 десятичное)
& = is a composite bitwise logical I. As usual And only with assignment.
UPDATE
val &= val - 1 // val = val & (val - 1) val = 5 // 101 val = val & (val - 1) // 101 & 100 = 100 val = val & (val - 1) // 100 & 011 = 0
Continue the table further, catch the pattern and understand the meaning
Would write more as a function is called, maybe all questions would disappear by themselves
@good , specifically about the operations ^ and & = you were told, but in general it is the counting of different digits in x and y.
val = x ^ y will set to val in one those bits that are different in x and y.
dist will get the result.
Operations with bits. ^ - XOR - exclusive or, the bit will be equal to one only if one number is set to 1, and the other to 0. & - AND - And, the bit will be equal to one only if it is set to 1 in two numbers. & = - AND with assignment.
Source: https://ru.stackoverflow.com/questions/161641/
All Articles