π’ Bit Manipulation
One-line summary: Operate directly on bits β XOR, AND, OR, shifts β for elegant O(1) tricks that would otherwise require O(n) logic.
Diagramβ
Conceptβ
| Operation | Symbol | Example | Result |
|---|---|---|---|
| AND | & | 5 & 3 | 1 |
| OR | | | 5 | 3 | 7 |
| XOR | ^ | 5 ^ 3 | 6 |
| NOT | ~ | ~5 | -6 |
| Left shift | << | 5 << 1 | 10 |
| Right shift | >> | 5 >> 1 | 2 |
Key XOR properties: a^a=0, a^0=a, commutative, associative.
Common Patternsβ
Find Single Numberβ
const singleNumber = (nums) => nums.reduce((acc, n) => acc ^ n, 0);
Check Even/Oddβ
const isEven = (n) => (n & 1) === 0;
Count Set Bits (Brian Kernighan)β
function countBits(n) {
let count = 0;
while (n > 0) {
n &= n - 1;
count++;
}
return count;
}
XOR Swapβ
let a = 5,
b = 3;
a ^= b;
b ^= a;
a ^= b;
Power of Two Checkβ
const isPowerOfTwo = (n) => n > 0 && (n & (n - 1)) === 0;
Pitfallsβ
- JS bitwise ops work on 32-bit signed integers β large numbers get truncated
~n = -(n+1)β use>>> 0to convert to unsigned if needed- XOR swap doesn't work if
aandbpoint to the same variable
Practice Problemsβ
Easy Problemsβ
Medium Problemsβ
Hard Problemsβ
Related Topicsβ
- Math
- School Basics β XOR swap covered there
β Back to Home Β· Β© sparshjaswal