Bit manipulation
Bit manipulation tricks can sometimes optimise your solution with a small number of operations and compact code. They appear in fewer problems than arrays or hash tables, but a few operations cover most of them.
Binary representation
In binary representation, the only possible digits are 0 and 1, and the scale factor is 2 instead of 10. For example, 110 in binary is 6 in decimal.
Binary to decimal
To convert a binary number to decimal, we multiply each digit by its scale and add the results. The scale starts at 1 for the last digit and doubles with every step to the left.
Decimal to binary
To convert a decimal number to binary, we divide it by 2.
The last bit of n is n % 2, and dividing n by 2 drops it.
Repeat until n is 0, and the bits come out from right to left.
Bitwise operations
AND (&)
Returns 1 only when both bits are 1.
OR (|)
Returns 1 when at least one of the bits is 1.
XOR (^)
Returns 1 when the bits are different.
NOT (~)
Flips every bit.
Left shift (<<)
Moves every bit k places to the left and fills the right with zeros.
Right shift (>>)
Moves every bit k places to the right and drops the last k bits.
Tricks
Check the last bit
n & 1 returns the last bit of n, because 1 is 00000001 and AND with 0 turns every other bit into 0.
Check bit k
(n >> k) & 1 returns bit k of n: the shift moves it to the last place, and & 1 keeps only that bit.
Set bit k
n | (1 << k) sets bit k to 1 and keeps the other bits, because 1 << k has a 1 only at bit k, and OR with 1 gives 1 while OR with 0 keeps the bit.
Clear bit k
n & ~(1 << k) sets bit k to 0 and keeps the other bits, because ~(1 << k) has a 0 only at bit k, and AND with 0 gives 0 while AND with 1 keeps the bit.
Toggle bit k
n ^ (1 << k) flips bit k and keeps the other bits, because 1 << k has a 1 only at bit k, and XOR with 1 flips the bit while XOR with 0 keeps it.
Remove the last 1 bit
n & (n - 1) removes the last 1 bit of n, because n - 1 turns that bit into 0 and every 0 after it into 1.