Core Module
12 min forge
Bit Manipulation
Learn how to talk to CPU in its native language. Master AND, OR, XOR, and the magic of Binary.
π€ Bit Manipulation: Low-Level Magic
Computers don't see numbers like 42; they see electrical pulses: 101010. Bit manipulation is using the foundational operators of logic to solve problems with extreme speed and zero memory.
π‘ The Logic (ELI5)
Think of a row of Light Switches:
- Every number is just a sequence of ON (1) and OFF (0) switches.
- AND (&): Both switches must be ON for the result to be ON.
- OR (|): If at least one switch is ON, the result is ON.
- XOR (^): If for two switches, exactly one is ON, the result is ON. (This is like a "Flip" operation).
- NOT (~): Flips every switch.
π The Deep Dive
The 4 Operators you MUST know
- AND (&):
5 & 3(101 & 011) = 001 (1). Useful for checking if a bit is set. - OR (|):
5 | 3(101 | 011) = 111 (7). Useful for setting a bit. - XOR (^):
5 ^ 3(101 ^ 011) = 110 (6). Legendary Property:A ^ A = 0. Useful for finding unique elements. - Shift (<<, >>): Moving bits left or right. Left shift by 1 is the same as multiplying by 2.
Common Tricks
- Check if even:
(n & 1) === 0 - Check if power of 2:
(n > 0) && (n & (n - 1)) === 0 - Toggle i-th bit:
n ^ (1 << i) - Clear i-th bit:
n & ~(1 << i)
π οΈ Code Forge: Finding the Single Number
One of the most famous bit manipulation interview questions.
javascript Standard/** * Find the number that appears only once in an array where every other number appears twice. * Logic: XORing a number with itself results in 0. (A ^ A = 0) * Logic: XORing with 0 results in the number itself. (A ^ 0 = A) */ function singleNumber(nums) { let result = 0; for (let num of nums) { result ^= num; } return result; } // Example const arr = [4, 1, 2, 1, 2]; console.log(singleNumber(arr)); // Output: 4
π― Interview Pulse
Binary representation of negative numbers
Research Two's Complement. It's the standard way computers store signed integers. To get a negative number's binary: take the positive binary, flip all bits, and add 1.
Top Questions
- Count set bits (Hamming Weight).
- Reverse bits of a 32-bit integer.
- Bitwise AND of numbers range.
- Divide two integers without using multiplication/division. π