Skip to the content

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:     3210

Each 0 or 1 is a bit. In JavaScript: (13).toString(2) gives "1101"; parseInt("1101", 2) gives 13.

The bitwise operators

OperatorNameRuleExample (5 = 101, 3 = 011)
&AND1 if both bits are 15 & 3 = 001 = 1
|OR1 if either bit is 15 | 3 = 111 = 7
^XOR1 if the bits are different5 ^ 3 = 110 = 6
~NOTFlips every bit~5 = -6
<<Left shiftMoves bits left; multiplies by 2 each step5 << 1 = 10
>>Right shiftMoves bits right; divides by 2 (keeps the sign)5 >> 1 = 2
>>>Unsigned right shiftRight 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

TaskCode
Is bit i set?(n >> i) & 1
Set bit in | (1 << i)
Clear bit in & ~(1 << i)
Toggle bit in ^ (1 << i)
Is n odd?(n & 1) === 1
Remove the lowest set bitn & (n - 1)
Is n a power of two?n > 0 && (n & (n - 1)) === 0
TypeScript
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").

TypeScript
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.

TypeScript
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.

TypeScript
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.)

TypeScript
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

WordMeaning
BinaryBase-2 numbers made of 0s and 1s
BitOne binary digit
AND / OR / XOR / NOTBitwise operators &, |, ^, ~
ShiftMoving bits left or right
BitmaskA number whose bits represent a set of flags
Hamming weightThe number of 1-bits

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.