Bit Manipulation · Pattern 2 of 6

Bit tricks: lowest set bit, powers of two and repeating patterns

A handful of one-liners do most of the work: n & (n - 1) clears the lowest set bit, n & -n keeps only it, n | (n + 1) sets the lowest unset bit, and XOR of 1..n repeats every 4 numbers.

3 variations · 7 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Count the set bits, or check for a power of two
  • Do something with the lowest set or unset bit
  • A formula for XOR of 1..n or a Gray code sequence
  • Split a number or a range into powers of two

The template

Tricks to remember
int hammingWeight(int n) {                // number of set bits
    int count = 0;
    for (; n != 0; n &= n - 1) count++;     // each step clears the lowest 1
    return count;
}

boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n - 1)) == 0;     // exactly one set bit
}

int setRightmostUnset(int n) {
    if ((n & (n + 1)) == 0) return n;       // all ones already (like 111)
    return n | (n + 1);                     // n + 1 flips the lowest 0 to 1
}

int xorUpTo(int n) {                        // 1 ^ 2 ^ ... ^ n
    switch (n % 4) {
        case 0: return n;
        case 1: return 1;
        case 2: return n + 1;
        default: return 0;
    }
}

int[] circularPermutation(int n, int start) {   // Gray code, rotated to start
    int[] res = new int[1 << n];
    for (int i = 0; i < res.length; i++) res[i] = start ^ i ^ (i >> 1);
    return res;
}

The variations

  1. 1The lowest set bit

    n & (n - 1) removes the lowest 1, so a loop runs once per set bit, and a power of two is a number with nothing left after one step. n & -n isolates that bit; to reach 0 with the fewest ± powers of two, subtract a lone 1 but add to a run of 1s so it carries into one bit.

  2. 2The lowest unset bit and aligned blocks

    n + 1 turns the lowest 0 into 1 and clears the 1s below it; OR with n puts them back. The lowbit x & -x also tells you the biggest aligned block starting at x, which is how a range of IP addresses splits into CIDR blocks.

    Now you solve
  3. 3Patterns that repeat

    Write out a few values and look for the cycle. XOR of 1..n goes n, 1, n + 1, 0 with period 4. The Gray code i ^ (i >> 1) changes one bit per step, and XOR with start rotates the cycle so it begins at start.

Mistakes to avoid

  • isPowerOfTwo without n > 0: zero passes the n & (n - 1) test, and in Java the most negative int does too.
  • Writing n & n - 1 == 0: comparison binds tighter than &, so wrap it as (n & (n - 1)) == 0.
  • Counting bits of a negative number in Python with the n & (n - 1) loop: it never ends. Mask with 0xFFFFFFFF first.
Next: XOR basics: cancel, compare and prefix XOR →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.