Bit Manipulation Patterns & Formulas
The 10 foundational bitwise patterns every software engineer must master for DSA and coding interviews.
💡 If you are preparing for DSA, a handful of bit manipulation patterns cover a massive percentage of interview questions. The secret is not blind memorization—it is understanding what the bits are doing under the hood.
Interactive Bitwise Sandbox
Interactive Bitwise Lab & Visualizer
Change numbers or bit indices and watch the bits transform in real-time.
💡 Removed the lowest set bit: 12 (1100) & 11 (1011) = 8 (1000)
The 5 Formulas to Memorize First
High-Yield Coren & 1n & (1 << i)n | (1 << i)n & ~(1 << i)n & (n - 1)n & -na ^ a = 0The Bigger Mental Model: The 4 Operations
Do not memorize these as disconnected formulas. Understand how the 4 basic bitwise operators manipulate masks.
Useful for checking, masking, and clearing specific bits.
Useful for turning on / setting specific bits without disturbing others.
Useful for toggling state, parity checks, and duplicate cancellation.
Useful for constructing inverted masks like ~(1 << i).
The 10 Bit Manipulation Patterns (Detailed Breakdown)
Every formula with internal mechanics, visual binary traces, and canonical code snippets.
Check whether a number is Even or Odd
n & 1In binary, every power of 2 ($2^1=2, 2^2=4, 2^3=8$) is inherently even. The only bit contributing an odd value ($2^0=1$) is the least significant bit (bit 0). If bit 0 is 1, the number is odd; otherwise, it is even.
5 = 101 -> last bit is 1 -> Odd 6 = 110 -> last bit is 0 -> Even 5 & 1: 1 0 1 (5) & 0 0 1 (1) ------- 0 0 1 != 0 (Odd)
if ((n & 1) == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}Check if the i-th bit is set
(n & (1 << i)) != 0Left-shifting 1 by i positions creates a mask with a 1 at position i and zeros everywhere else. AND-ing this mask with n yields a non-zero value if and only if bit i is set.
n = 5 (binary: 101), check bit 2: 1 << 2: 0 0 1 0 1 0 (1 << 1) 1 0 0 (1 << 2) Then: 1 0 1 (5) & 1 0 0 (4) ------- 1 0 0 != 0 -> Bit 2 is SET!
// Check whether bit i is set (0-indexed) boolean isSet = (n & (1 << i)) != 0; // Alternative right-shift version: boolean isSetShifted = ((n >> i) & 1) == 1;
Set the i-th bit
n | (1 << i)Because 0 | 1 = 1 and 1 | 1 = 1, OR-ing with (1 << i) guarantees bit i becomes 1. Because 0 | x = x, all other bits remain identical to their original values.
n = 5 (101), set bit 1: 1 << 1 = 010 1 0 1 (5) | 0 1 0 (2) ------- 1 1 1 = 7
// Set bit i to 1 n = n | (1 << i);
Clear the i-th bit
n & ~(1 << i)The sub-expression ~(1 << i) is the secret: it creates a mask where every single bit is 1 except for bit i, which is 0. AND-ing with this mask zeroes out bit i while leaving all other bits intact.
n = 7 (111), clear bit 1: 1 << 1 = 010 ~010 = 101 (inverted mask) 1 1 1 (7) & 1 0 1 (5) ------- 1 0 1 = 5
// Clear bit i to 0 n = n & ~(1 << i);
Toggle the i-th bit
n ^ (1 << i)XOR has the property that 0 ^ 1 = 1 and 1 ^ 1 = 0. Therefore, XOR-ing any bit with 1 flips it, while XOR-ing with 0 preserves it.
n = 5 (101), toggle bit 1: 1 << 1 = 010 1 0 1 (5) ^ 0 1 0 (2) ------- 1 1 1 = 7 (if toggled again, becomes 5)
// Toggle bit i n = n ^ (1 << i);
Remove the lowest set bit (Brian Kernighan)
n = n & (n - 1)Subtracting 1 from n flips all bits from the rightmost set bit downward. When you compute n & (n - 1), the rightmost 1 and all lower bits become 0, while all higher bits remain unchanged.
n = 12 (binary: 1100) n - 1 = 11 (binary: 1011) 1 1 0 0 (12) & 1 0 1 1 (11) --------- 1 0 0 0 (8) -> rightmost 1 was dropped!
// Count number of set bits (Hamming Weight) in O(set bits) time:
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;Get / Isolate the lowest set bit
n & -nTwo's complement representation defines -n as ~n + 1. Inverting n and adding 1 flips all bits up to the lowest set bit, leaving only the lowest set bit matching between n and -n.
n = 12: 12 = 0000 1100 -12 = 1111 0100 (two's complement: ~12 + 1) 0000 1100 (12) & 1111 0100 (-12) ----------- 0000 0100 = 4 (the isolated lowest set bit!)
// Isolate the lowest set bit int lowest = n & -n;
Check if a number is a power of 2
n > 0 && (n & (n - 1)) == 0A positive power of 2 (1, 2, 4, 8, 16, 32...) has exactly one set bit in its binary representation. Removing its lowest set bit via n & (n - 1) must result in exactly 0.
n = 8 (1000) n - 1 = 7 (0111) 1 0 0 0 (8) & 0 1 1 1 (7) --------- 0 0 0 0 == 0 -> Is power of 2! n = 10 (1010) n - 1 = 9 (1001) 1 0 1 0 (10) & 1 0 0 1 (9) --------- 1 0 0 0 != 0 -> Not a power of 2!
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}XOR Identity & Cancellation Tricks
x ^ 0 = x and x ^ x = 0Because XOR is both commutative (a ^ b = b ^ a) and associative ((a ^ b) ^ c = a ^ (b ^ c)), XOR-ing an array where every element appears twice except one causes all duplicate pairs to cancel out to 0.
Array: [4, 1, 2, 1, 2] Re-ordered conceptually: (1 ^ 1) ^ (2 ^ 2) ^ 4 = 0 ^ 0 ^ 4 = 4
// LeetCode 136: Single Number
public int singleNumber(int[] nums) {
int ans = 0;
for (int x : nums) {
ans ^= x;
}
return ans;
}
// Java Stream one-liner:
// return IntStream.of(nums).reduce(0, (a, b) -> a ^ b);Swap two numbers using XOR
a ^= b; b ^= a; a ^= b;Uses the cancellation property of XOR. Step 1 packs both values into a. Step 2 extracts original a into b. Step 3 extracts original b into a.
Initial: a = 5, b = 7 1. a = a ^ b -> a = 5 ^ 7 2. b = b ^ a -> b = 7 ^ (5 ^ 7) = (7 ^ 7) ^ 5 = 0 ^ 5 = 5 3. a = a ^ b -> a = (5 ^ 7) ^ 5 = (5 ^ 5) ^ 7 = 0 ^ 7 = 7 Final: a = 7, b = 5
// In-place XOR Swap: a ^= b; b ^= a; a ^= b; // IMPORTANT NOTE: // Do not use this in real production code. Modern compilers optimize temp = a; a = b; b = temp; better, // and XOR swap fails if a and b reference the exact same memory address (a[i] ^= a[i] produces 0).
Quick-Reference Cheat Sheet Table
Ready for quick revision| Problem / Goal | Formula | Key Insight | Copy |
|---|---|---|---|
| Check if number is Odd/Even | n & 1 | 0 = Even, 1 = Odd | |
| Check if i-th bit is set | (n & (1 << i)) != 0 | Non-zero means set | |
| Set i-th bit to 1 | n | (1 << i) | Forces i-th bit to 1 | |
| Clear i-th bit to 0 | n & ~(1 << i) | Forces i-th bit to 0 | |
| Toggle i-th bit | n ^ (1 << i) | Flips 0 -> 1 and 1 -> 0 | |
| Remove lowest set bit | n & (n - 1) | Brian Kernighan algorithm | |
| Get lowest set bit (isolate) | n & -n | Used in Fenwick trees & BIT | |
| Check if power of 2 | n > 0 && (n & (n - 1)) == 0 | Has exactly one 1-bit | |
| Single Number (Unique in pairs) | XOR all elements | x ^ x = 0; x ^ 0 = x | |
| Swap two numbers | a ^= b; b ^= a; a ^= b; | Conceptual trick (avoid in prod) |
The Intuition Decision Tree
When you encounter an interview problem involving bits:
↓
Are you testing or reading state?
→ Use: n & (1 << i) or n & 1
↓
Are you flipping or setting a flag?
→ Use: n | (1 << i) or n ^ (1 << i)
↓
Are you eliminating or counting set bits?
→ Use: n & (n - 1)
↓
Are you isolating powers of 2 or tree positions?
→ Use: n & -n
↓
Are elements appearing in pairs with one exception?
→ Use XOR accumulation: a ^ a = 0