Lesson 7 · Problem-solving methods

Bit Manipulation

Bit manipulation works on the binary digits of an integer directly. A few identities replace loops with single operations, turn small sets into integers, and solve some problems in O(1) extra space.

Bit Manipulation concept diagramA visual explanation of the layout and operations shown in this lesson.the AND of n and n − 1 clears the lowest set bitn = 121100AND operationn − 1 = 111011result = 81000one bit cleared per step, so the loop counts set bits in O(set bits)
1

The Six Bitwise Operators

Bitwise operators work on an integer's binary digits one column at a time, not on its value. Each of the six has one job worth remembering, shown in the table. Clearing bit i combines two of them: x & ~(1 << i). Reading it is (x >> i) & 1.

Shifts are where languages differ. For a non-negative x, x << k multiplies by 2^k and x >> k divides by 2^k, dropping the remainder. On a negative number an arithmetic shift copies the sign bit in from the left, while a logical shift fills with 0s and makes the result positive. Java and JavaScript have both: >> is arithmetic and >>> is logical. C++20 defines >> on signed values as arithmetic; C leaves it to the compiler, though the major ones all do the same. Use unsigned types in C and C++ when you want a logical shift.

Shifting by the type's width or more is undefined behaviour in C and C++. Java takes the count modulo 32 for an int (64 for a long), so 1 << 32 is 1, not 0.

Python integers have no fixed width. 1 << 100 is an ordinary number, and a negative number behaves as if it had endless 1s on the left, so ~5 is −6 and -1 >> 10 is still −1. To get 32-bit behaviour in Python, mask with & 0xFFFFFFFF.

The operators and what each is used for
OperatorResult bitTypical use
& AND1 where both are 1Mask or test a bit: x & (1 << i)
| OR1 where either is 1Set a bit: x | (1 << i)
^ XOR1 where they differToggle a bit: x ^ (1 << i)
~ NOTevery bit flipped~x == −x − 1 in two's complement
<< left shiftbits move up, 0s fill inMultiply by 2^k
>> right shiftbits move downDivide by 2^k (sign handling varies)
  • Precedence: in C, x & 1 == 0 means x & (1 == 0), which is always 0; Java refuses to compile it. Bracket every bitwise expression
  • 1 << 31 does not fit a signed 32-bit int in C; write 1u << 31 or use a 64-bit type
  • XOR swap (a ^= b; b ^= a; a ^= b) is a curiosity: slower than a temporary, and it zeroes the value when both names refer to the same variable
2

Clearing and Isolating the Lowest Set Bit

  1. Set count = 0
  2. While n is not 0: set n = n & (n − 1) and add 1 to count
  3. Return count: the loop ran once per set bit

Two bit manipulation tricks carry most interview problems, and both are about the lowest 1. n & (n − 1) clears the lowest set bit. Subtracting 1 turns that lowest 1 into 0 and every 0 below it into 1, and leaves the higher bits alone. ANDing with the original keeps the higher bits, where both agree, and zeroes the rest. For 12 (1100), n − 1 is 1011 and the AND is 1000.

Repeating it until n is 0 counts the set bits. This is Brian Kernighan's algorithm, and the code on this page runs it on 12. It loops once per set bit, not once per bit position, so a number with three 1s takes three passes whether it is 8 or 64 bits wide.

The same identity tests for a power of two. A power of two has exactly one 1, so clearing it leaves 0: the test is n > 0 and (n & (n − 1)) == 0. The n > 0 part matters, because 0 & −1 is also 0.

n & −n keeps only the lowest set bit. In two's complement −n is ~n + 1. Inverting turns the lowest 1 into 0 and the 0s below it into 1s; adding 1 carries through those and stops exactly at the lowest 1's position. So n and −n share only that bit: 12 & −12 = 4. The Fenwick tree moves through its array with this value.

Prefer the built-in count where there is one: int.bit_count() in Python 3.10+ (bin(x).count('1') before that), Integer.bitCount in Java, std::popcount in C++20 or __builtin_popcount in GCC and Clang. On CPUs with a POPCNT instruction these compile to a single instruction.

The hand-written loop hides a trap with negative input. In Python a negative n has endless leading 1s, so the loop clears one per pass forever and never reaches 0; mask with n & 0xFFFFFFFF first. In C, use an unsigned type, because subtracting 1 from the most negative int overflows.

3

XOR Cancellation

XOR has three properties that make it useful: x ^ x = 0, x ^ 0 = x, and the order of operations does not matter. XOR a list together and every value that appears twice cancels, wherever its copies are, leaving only what appears an odd number of times.

Single number. When every value appears twice except one, XOR everything; the pairs vanish and the single value is left. That is O(n) time and O(1) space, with no hash set and no sorting. On [4, 1, 2, 1, 2] the running value goes 4, 5, 7, 6, 4.

Missing number. For an array holding 0 to n with one value missing, XOR all the indices 0 to n and all the values. Every present number appears twice and cancels; the missing one appears once. Unlike adding everything up and subtracting, this cannot overflow.

Two single numbers. When two values a and b appear once, XORing everything gives a ^ b, which is not 0. Any set bit in it is a position where a and b differ; the lowest one, x & −x, is the easy pick. Split the array by that bit and XOR each half: each half holds one answer plus complete pairs.

XOR only cancels even counts. A value that appears three times leaves one copy behind and mixes into the answer. Problems where values repeat three times need a different tool: count how many numbers have each bit set, and take each count modulo 3.

Key reference

Terms, operations, and practical uses

Core vocabulary

  • BitmaskAn integer used to represent a set of boolean flags or items, where each bit corresponds to one item's presence (1) or absence (0).
  • Bitwise XOR (^)An operation that outputs 1 only if the two input bits are different. Useful for toggling bits.
  • Shift (<<, >>)Moving bits to the left (multiplying by powers of 2) or right (dividing by powers of 2).

Common operations

  • Set a bitUse OR: mask | (1 << i) sets the i-th bit to 1.
  • Clear a bitUse AND with NOT: mask & ~(1 << i) sets the i-th bit to 0.
  • Check a bitUse AND: (mask & (1 << i)) != 0 checks if the i-th bit is 1.

Advanced tricks

  • Isolate Lowest Set BitThe expression x & -x returns the value of the lowest set bit in x.
  • Clear Lowest Set BitThe expression x & (x - 1) turns off the lowest set bit in x.
  • Check Power of 2A number is a power of 2 if x > 0 and (x & (x - 1)) == 0.
Implementation

Code in Python, C++ and Java

def count_set_bits(n):
    count = 0
    while n:
        n &= n - 1          # clear the lowest set bit
        count += 1
    return count

print(count_set_bits(12))   # 2
#include <iostream>
using namespace std;

int countSetBits(int n) {
    int count = 0;
    while (n) {
        n &= n - 1;         // clear the lowest set bit
        count++;
    }
    return count;
}

int main() {
    cout << countSetBits(12) << '\n';   // 2
}
class Main {
    static int countSetBits(int n) {
        int count = 0;
        while (n != 0) {
            n &= n - 1;     // clear the lowest set bit
            count++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countSetBits(12));   // 2
    }
}
Watch it run

Step through it

Running on n = 12, then [4, 1, 2, 1, 2]

n = 121286432168421n0000110012set bits: ? (2 hidden among 8 positions)
Step 1

12 in binary is 0000 1100

Every integer is a row of bits, each worth a power of two. 12 = 8 + 4, so only the 8 and 4 columns hold a 1. Counting set bits means counting those 1s, and a naive loop would test all 8 columns (32 for an int) to find two of them.

Output
1 / 13
4

Integers as Sets: Bitmasks

A bitmask uses an integer as a set of up to 64 elements: bit i is 1 when element i is in the set. Set operations become single instructions instead of hashing and allocation.

Union is a | b, intersection a & b, difference a & ~b, symmetric difference a ^ b, membership (mask >> i) & 1, and size is the popcount.

Every subset of n elements is a number from 0 to 2^n − 1, so looping over that range visits all of them; this is one way to solve Subsets. To visit only the subsets of a given mask, use s = (s − 1) & mask, starting from s = mask and stopping at 0 (handle the empty set separately).

The main algorithmic use is bitmask dynamic programming, where part of the state is the set of items already used. The travelling salesman problem over n cities uses the state (current city, visited mask), which is O(2ⁿ · n²) time: workable to about n = 20, where trying all n! orders is hopeless.

Outside algorithms, bitmasks are everywhere. Unix file permissions are bits: read 4, write 2, execute 1, so chmod 755 means 111 101 101. Feature flags and option sets work the same way, and chess engines store each piece type as a 64-bit bitboard, one bit per square.

Two limits. A single integer holds at most 64 elements; past that, use an array of words or a bitset type such as std::bitset or java.util.BitSet. And a wrong shift amount gives a silently wrong answer rather than an error, so name masks with constants instead of writing raw numbers.

  • Union |, intersection &, difference & ~, size = popcount
  • Enumerate the subsets of a mask with s = (s − 1) & mask
  • Bitmask DP handles about 20 items; one integer holds at most 64