Lesson 149 of 296
Bit manipulation
What you will learn
- Binary numbers
- The bitwise operators
- Common bit tricks
- JavaScript's 32-bit limit
- Single Number, Counting Bits, Missing Number
On this page
Binary in one minute
Computers store numbers in binary (base 2): each position is a power of 2.
13 in binary: 1101 = 8 + 4 + 0 + 1
position: 3210Each 0 or 1 is a bit. In JavaScript: (13).toString(2) gives "1101"; parseInt("1101", 2) gives 13.
The bitwise operators
| Operator | Name | Rule | Example (5 = 101, 3 = 011) |
|---|---|---|---|
& | AND | 1 if both bits are 1 | 5 & 3 = 001 = 1 |
| | OR | 1 if either bit is 1 | 5 | 3 = 111 = 7 |
^ | XOR | 1 if the bits are different | 5 ^ 3 = 110 = 6 |
~ | NOT | Flips every bit | ~5 = -6 |
<< | Left shift | Moves bits left; multiplies by 2 each step | 5 << 1 = 10 |
>> | Right shift | Moves bits right; divides by 2 (keeps the sign) | 5 >> 1 = 2 |
>>> | Unsigned right shift | Right shift, filling with zeros | -1 >>> 0 = 4294967295 |
JavaScript's 32-bit warning
JavaScript numbers are 64-bit floating point (Lesson 49), but bitwise operators convert them to 32-bit signed integers first. Numbers above about 2.1 billion get cut. For larger values, use BigInt (5n & 3n).
XOR's special properties
x ^ x = 0(a number cancels itself)x ^ 0 = x- Order does not matter:
a ^ b ^ a = b
Common tricks
| Task | Code |
|---|---|
| Is bit i set? | (n >> i) & 1 |
| Set bit i | n | (1 << i) |
| Clear bit i | n & ~(1 << i) |
| Toggle bit i | n ^ (1 << i) |
| Is n odd? | (n & 1) === 1 |
| Remove the lowest set bit | n & (n - 1) |
| Is n a power of two? | n > 0 && (n & (n - 1)) === 0 |
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}A power of two has exactly one 1-bit (8 = 1000). Subtracting 1 flips it and everything below (0111), so AND gives 0.
Number of 1 Bits
Problem (LeetCode 191): count the 1-bits (the "Hamming weight").
function hammingWeight(n: number): number {
let count = 0;
let value = n >>> 0;
while (value !== 0) {
value &= value - 1;
count++;
}
return count;
}value & (value - 1) removes one set bit each time, so the loop runs once per 1-bit. >>> 0 treats the input as unsigned 32-bit.
Single Number
Problem (LeetCode 136): every number appears twice except one. Find it in O(n) time and O(1) space.
XOR everything: pairs cancel to 0, leaving the single one.
function singleNumber(nums: number[]): number {
let result = 0;
for (const n of nums) result ^= n;
return result;
}[4, 1, 2, 1, 2] → 4 ^ 1 ^ 2 ^ 1 ^ 2 → 4.
Counting Bits
Problem (LeetCode 338): for every i from 0 to n, the number of 1-bits in i.
A DP trick: i >> 1 is i without its last bit, whose count is already known. Add the last bit back.
function countBits(n: number): number[] {
const result = new Array<number>(n + 1).fill(0);
for (let i = 1; i <= n; i++) {
result[i] = result[i >> 1]! + (i & 1);
}
return result;
}O(n).
Missing Number
Problem (LeetCode 268): the array has n distinct numbers from 0 to n, one missing. Find it.
XOR all indexes 0..n and all values: everything present cancels, leaving the missing number. (The sum formula n(n+1)/2 - sum also works.)
function missingNumber(nums: number[]): number {
let result = nums.length;
for (let i = 0; i < nums.length; i++) {
result ^= i ^ nums[i]!;
}
return result;
}Where bits appear in real code
- Permission flags: READ = 1, WRITE = 2, DELETE = 4; a user's permissions are combined with
|and checked with&. - Feature flags, compact storage, hashing, graphics, network masks.
- Bitmask DP: representing a set of up to about 20 items as the bits of one number.
How to say it in an interview
"Bitwise operators work on the 32-bit integer form of numbers in JavaScript, so for larger values I use BigInt. XOR cancels equal values, so XOR-ing everything finds the single number or the missing number in O(1) space. n AND n minus 1 removes the lowest set bit, which counts bits efficiently and tests powers of two. Counting Bits uses result of i equals result of i shifted right plus the last bit. In real systems I see bits used for permission and feature flags."
Key words
| Word | Meaning |
|---|---|
| Binary | Base-2 numbers made of 0s and 1s |
| Bit | One binary digit |
| AND / OR / XOR / NOT | Bitwise operators &, |, ^, ~ |
| Shift | Moving bits left or right |
| Bitmask | A number whose bits represent a set of flags |
| Hamming weight | The number of 1-bits |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.