Math Fundamentals18 sections · 814 units
Open in Course

Common Bit Tricks

Useful patterns

Here are bit manipulation patterns you will see repeatedly in interviews and production code.

1.1. Check if nn is even: n&1=0n \& 1 = 0.

2.2. Set the kk-th bit: n(1<<k)n | (1 << k).

3.3. Clear the kk-th bit: n&(1<<k)n \& \sim(1 << k).

4.4. Toggle the kk-th bit: n(1<<k)n \wedge (1 << k).

5.5. Check if nn is a power of 2: n>0n > 0 and n&(n1)=0n \& (n - 1) = 0.

These tricks replace loops with single operations. Instead of checking divisibility by 2, you check the last bit. Instead of looping to set a bit, you use OR with a mask. Memorize these patterns.