Bit Manipulation

Operators, two's complement, essential tricks, bitmasks as sets, and the interview problems they solve in O(1) space.

Intermediate 4 min readLesson 17 of 18 Interview Q&A

Integers are stored as bits. Operating on those bits directly is extremely fast (one CPU instruction) and lets you pack many booleans into one number. Bit tricks appear in hashing, compression, cryptography, graphics, permissions, chess engines, Bloom filters and many interview questions.

0706150413120110
45 in 8-bit binary = 32 + 8 + 4 + 1. Bit i has value 2ⁱ (bit 0 is on the right).

The operators

OperatorSymbolRuleExample (a = 1100, b = 1010)
AND&1 if both are 11000
OR|1 if either is 11110
XOR^1 if they differ0110
NOT~flip every bit~1100 = …0011
Left shift<<multiply by 2ᵏ0011 << 2 = 1100
Right shift (arithmetic)>>divide by 2ᵏ, keeps the sign-8 >> 1 = -4
Right shift (logical)>>>fills with zeros (Java, JS)-1 >>> 28 = 15

Two's complement

Signed integers use two's complement: the top bit has value −2ⁿ⁻¹. Negating a number is ~x + 1. So -1 is all ones, and the range of a 32-bit int is −2³¹ … 2³¹ − 1. Full details in Computer arithmetic.

Essential tricks

GoalExpression
Is bit i set?(x >> i) & 1
Set bit ix | (1 << i)
Clear bit ix & ~(1 << i)
Toggle bit ix ^ (1 << i)
Lowest set bitx & -x
Clear lowest set bitx & (x - 1)
Is x a power of two?x > 0 && (x & (x - 1)) == 0
Is x odd?(x & 1) == 1
Multiply / divide by 2ᵏx << k / x >> k
Swap without tempa ^= b; b ^= a; a ^= b;
All ones in the low k bits(1 << k) - 1

XOR: the interview superpower

XOR's properties — x ^ x = 0, x ^ 0 = x, commutative and associative — make paired values cancel out.

Single number: every element appears twice except one
int singleNumber(int[] nums) {
    int x = 0;
    for (int n : nums) x ^= n;       // pairs cancel, the single one remains
    return x;
}

// Missing number in 0..n
int missingNumber(int[] nums) {
    int x = nums.length;
    for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
    return x;
}

More XOR problems in Bitwise XOR.

Counting bits

int popcount(int x) {
    int c = 0;
    while (x != 0) { x &= x - 1; c++; }   // Kernighan: one iteration per set bit
    return c;
}
// Built-in: Integer.bitCount(x), Long.numberOfTrailingZeros(x), Integer.highestOneBit(x)

int[] countBits(int n) {                 // DP: bits(i) = bits(i >> 1) + (i & 1)
    int[] res = new int[n + 1];
    for (int i = 1; i <= n; i++) res[i] = res[i >> 1] + (i & 1);
    return res;
}

Bitmasks as sets

A number with n bits represents a subset of n items: bit i set ⇔ item i included. Union is |, intersection &, difference a & ~b. Enumerating all subsets is a loop from 0 to 2ⁿ − 1.

// All subsets of nums
List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    int n = nums.length;
    for (int mask = 0; mask < (1 << n); mask++) {
        List<Integer> s = new ArrayList<>();
        for (int i = 0; i < n; i++) if ((mask >> i & 1) == 1) s.add(nums[i]);
        res.add(s);
    }
    return res;
}

// Iterate all submasks of mask
for (int sub = mask; sub > 0; sub = (sub - 1) & mask) { /* ... */ }

Bitmasks also encode flags and permissions (Unix file modes rwxr-xr-x = 0755), feature sets, chess boards (bitboards: 64 squares in one long), and the state in bitmask DP.

Key takeaways
  • Know &, |, ^, ~, shifts, and two's complement.
  • x & (x−1) clears the lowest set bit; x & −x isolates it.
  • XOR cancels pairs: single number, missing number, swap.
  • Bitmasks represent subsets of up to ~20–30 items compactly.
Interview questions
QReverse the bits of a 32-bit unsigned integer.easy

Loop 32 times: res = (res << 1) | (n & 1); n >>>= 1;. For repeated calls, use a 256-entry lookup table for bytes, or swap halves, then quarters, and so on with masks (O(log w)).

QAdd two integers without using + or −.medium

a ^ b adds without carries; (a & b) << 1 is the carry. Repeat a, b = a ^ b, (a & b) << 1 until b is 0. In Python, mask to 32 bits to terminate with negative numbers.

QEvery element appears three times except one. Find it in O(1) space.hard

Count each of the 32 bit positions across all numbers modulo 3; the remainders form the single number. Or use the two-variable state machine ones = (ones ^ x) & ~twos; twos = (twos ^ x) & ~ones.