Bit Manipulation
A number is a row of light switches. Binary tricks flip or read those switches directly. One trick turns off the rightmost lit switch in a single move, so counting the lit ones takes one move per light, and the dark ones are skipped.
2 · Watch
Bit Manipulation in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Number of 1 Bits
or try
A whole number from 0 to 255.172 in binary is 10101100. Count starts at 0.Step 1 of 14. 172 is 1 0 1 0 1 1 0 0 in binary.
Step 1 of 14
solution.ts
function hammingWeight(n: number): number {
let count = 0;
while (n !== 0) {
n &= n - 1;
count++;
}
return count;
}
▶ marks the line running now
4 · Your turn
0 of 5 problems solved
Start from this
// n & (n - 1) clears the lowest 1 bit.
let count = 0;
while (n !== 0) {
n &= n - 1;
count++;
}
// x ^ x is 0, so every pair cancels and the lone value stays.
let lone = 0;
for (const num of nums) lone ^= num;
// Read bit i, set it, or clear it.
const bit = (n >> i) & 1;
n |= 1 << i;
n &= ~(1 << i);Easy ways to go wrong
- Using >> on a negative number in JavaScript. Use >>> to shift in zeros.
- Forgetting Python ints never overflow. Mask with 0xFFFFFFFF to act like 32 bits.
- Leaving out brackets. === runs before & in JavaScript, so write (n & 1) === 1.
- Easy01
Number of 1 Bits
The one you just watched. Write it from memory.
n & (n − 1) clears the lowest 1 bit.
- Time
- O(1)
- Space
- O(1)
- Easy02
Counting Bits
Reuse the count for i >> 1.
bits(i) = bits(i >> 1) + (i & 1).
- Time
- O(n)
- Space
- O(n)
Also works with 1-D DP.
- Easy03
Reverse Bits
Shift off one end, onto the other.
Shift bits off one end and onto the other.
- Time
- O(1)
- Space
- O(1)
- Easy04
Missing Number
XOR cancels every pair.
XOR everything, or compare against the expected sum.
- Time
- O(n)
- Space
- O(1)
Also works with Arrays & Hashing or Math & Geometry.
- Medium05
Sum of Two Integers
XOR adds, AND finds the carries.
XOR gives the sum without carries, AND gives the carries. Repeat.
- Time
- O(1)
- Space
- O(1)