Workspace Bit Manipulation
0d
DSA Cheat Sheets

Bit manipulation formulas

For nonnegative 32-bit inputs, clear the lowest set bit once per loop iteration.

Test bit k(x >> k) & 1Use a valid shift count
Toggle bit kx XOR (1 << k)Each toggle reverses that bit
Clear lowest onex & (x−1)Works for positive x
Power of twox > 0 and (x & (x−1)) == 0Zero is excluded

Python

def count_ones(x):
    count = 0
    while x:
        x &= x-1
        count += 1
    return count

C++

int countOnes(unsigned x) {
  int count = 0;
  while (x) { x &= x-1; ++count; }
  return count;
}

Java

static int countOnes(int x) {
  int count = 0;
  while (x != 0) { x &= x-1; count++; }
  return count;
}