Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 10 minutesNeeds: binary numbersTime O(k)Space O(1)

2 · Watch

Bit Manipulation in 60 seconds

172 in binary is 10101100. Checking all eight bits works, but half of those checks land on zeros.

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.
  1. Easy01

    Number of 1 Bits

    LeetCode 191 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  2. Easy02

    Counting Bits

    LeetCode 338 · Blind 75 · NeetCode 150

    Reuse the count for i >> 1.

  3. Easy03

    Reverse Bits

    LeetCode 190 · Blind 75 · NeetCode 150

    Shift off one end, onto the other.

  4. Easy04

    Missing Number

    LeetCode 268 · Blind 75 · NeetCode 150

    XOR cancels every pair.

  5. Medium05

    Sum of Two Integers

    LeetCode 371 · Blind 75 · NeetCode 150

    XOR adds, AND finds the carries.

THAT’S ALL 20See every pattern