Bit Manipulation
Operators, two's complement, essential tricks, bitmasks as sets, and the interview problems they solve in O(1) space.
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.
The operators
| Operator | Symbol | Rule | Example (a = 1100, b = 1010) |
|---|---|---|---|
| AND | & | 1 if both are 1 | 1000 |
| OR | | | 1 if either is 1 | 1110 |
| XOR | ^ | 1 if they differ | 0110 |
| 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
| Goal | Expression |
|---|---|
| Is bit i set? | (x >> i) & 1 |
| Set bit i | x | (1 << i) |
| Clear bit i | x & ~(1 << i) |
| Toggle bit i | x ^ (1 << i) |
| Lowest set bit | x & -x |
| Clear lowest set bit | x & (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 temp | a ^= 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.
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;
}from functools import reduce
from operator import xor
def single_number(nums):
return reduce(xor, nums, 0) # pairs cancel
def missing_number(nums):
x = len(nums)
for i, n in enumerate(nums):
x ^= i ^ n
return xconst singleNumber = (nums: number[]) => nums.reduce((x, n) => x ^ n, 0);
function missingNumber(nums: number[]): number {
let x = nums.length;
nums.forEach((n, i) => (x ^= i ^ n));
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;
}def popcount(x: int) -> int:
c = 0
while x:
x &= x - 1 # Kernighan
c += 1
return c
# Built-in: x.bit_count() (3.10+), bin(x).count("1"), x.bit_length()
def count_bits(n):
res = [0] * (n + 1)
for i in range(1, n + 1):
res[i] = res[i >> 1] + (i & 1)
return resfunction popcount(x: number): number {
let c = 0;
while (x !== 0) { x &= x - 1; c++; }
return c;
}
// JS bitwise operators work on 32-bit signed ints! Use BigInt for wider values.
// Math.clz32(x) counts leading zeros.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) { /* ... */ }def subsets(nums):
n = len(nums)
return [[nums[i] for i in range(n) if mask >> i & 1] for mask in range(1 << n)]
# Iterate all submasks of mask
sub = mask
while sub:
# ... use sub ...
sub = (sub - 1) & maskfunction subsets(nums: number[]): number[][] {
const res: number[][] = [];
for (let mask = 0; mask < 1 << nums.length; mask++)
res.push(nums.filter((_, i) => (mask >> i) & 1));
return res;
}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.
- Know &, |, ^, ~, shifts, and two's complement.
x & (x−1)clears the lowest set bit;x & −xisolates it.- XOR cancels pairs: single number, missing number, swap.
- Bitmasks represent subsets of up to ~20–30 items compactly.
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.