Bit Manipulation
Welcome to the Bit Manipulation section of JDCodebase! Bit manipulation allows you to solve problems in constant time using binary logic. It’s a favorite topic in coding interviews due to its efficiency and cleverness.
What You’ll Learn
- Understanding bits and binary representation
- Common bitwise operators: AND, OR, XOR, NOT, shifts
- Tricks for checking even/odd, swapping, counting bits
- Set, unset, toggle, and check bits at specific positions
- Optimizing solutions using bit masks and properties
JavaScript Bitwise Operators
a & b: Bitwise AND — 1 only if both bits are 1.
Before: 5 & 3 Code: 5 & 3; // 101 & 011 = 001 After: 1
a | b: Bitwise OR — 1 if either bit is 1.
Before: 5 | 3 Code: 5 | 3; // 101 | 011 = 111 After: 7
a ^ b: Bitwise XOR — 1 if bits are different.
Before: 5 ^ 3 Code: 5 ^ 3; // 101 ^ 011 = 110 After: 6
~a: Bitwise NOT — inverts bits (two's complement).
Before: ~5 Code: ~5; // ~00000101 = 11111010 After: -6
a << n: Left shift — multiplies by 2ⁿ.
Before: 3 << 2 Code: 3 << 2; After: 12
a >> n: Right shift — divides by 2ⁿ (signed).
Before: 8 >> 1 Code: 8 >> 1; After: 4
a >>> n: Unsigned right shift (zero-fill).
Before: -8 >>> 1 Code: -8 >>> 1; After: 2147483644
Try This Example
Find the one number that appears once while all others appear twice.
function findSingleNumber(nums) { let result = 0; for (let num of nums) { result ^= num; // XOR cancels out duplicate values } return result; }
Input: [4, 1, 2, 1, 2]
Expected Output: 4