Courses / DSA Patterns for Working Engineers / Chapter 28
Module 9 · Bits, maths and mixed practice · Chapter 28 of 39
Bitwise Manipulation: Masks, XOR and the 32-Bit Trap
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Math and Geometry: Precision, Primes, Powers and Points.
Part 1 · Introduction to bitwise manipulation
Bits, masks and negative numbers
Permission flags, feature switches, checksums and compact sets all live inside single integers, and bitwise operators read and change them directly. This chapter teaches the operators, a few identities that replace loops, and the 32-bit limit that JavaScript puts on them.
A bit is a digit that is 0 or 1. Every integer is a row of bits, and each position has a place value that doubles as you move left: 1, 2, 4, 8 and so on. The number 44 is 32 + 8 + 4, so its bits are 101100. A bitwise operator works on two numbers one position at a time, which means you can treat one integer as a row of 32 independent yes-or-no flags. That is why a file permission, a set of enabled features or a small set of seat numbers fits in one number and can be copied, compared and combined in a single step.
A value used to select or change particular bits is called a mask. To test a flag you AND the number with a mask that has only that bit set. To set it you OR with the mask, and to clear it you AND with the inverted mask. Every trick in this chapter is a way of building the right mask, or a way of making an operator do the work of a loop.
| Operator | Meaning | Example |
|---|---|---|
| a & b | each bit is 1 only if both bits are 1 | 5 & 3 gives 1 |
| a | b | each bit is 1 if either bit is 1 | 5 | 3 gives 7 |
| a ^ b | each bit is 1 if exactly one bit is 1 (exclusive or) | 5 ^ 3 gives 6 |
| ~a | every bit is flipped | ~5 gives -6 |
| a << k | bits move left by k places, which multiplies by 2 to the power k |
Two's complement and the 32-bit rule
Computers store a negative number as its two's complement: the bit pattern of the positive number, flipped, plus one. In 8 bits the number 5 is 00000101, so -5 is 11111011. The leftmost bit then acts as a sign: it is 1 for every negative number. The identity -x = ~x + 1 follows from this definition, and we will use it in a moment. The run prints the low 8 bits of 5 and -5, and checks the identity.
const bits8 = (x: number) => (x & 0xff).toString(2).padStart(8, '0') console.log('5 in 8 bits ', bits8(5)) console.log('-5 in 8 bits', bits8(-5)) console.log('~5 + 1', ~5 + 1)
5 in 8 bits 00000101 -5 in 8 bits 11111011 ~5 + 1 -5
JavaScript numbers are 64-bit floating-point values, but the bitwise operators do not use that format (the MDN pages for the bitwise operators describe the 32-bit conversion and the discarded high bits). Each operand is first converted to a signed 32-bit integer: the fractional part is dropped, and the value wraps around modulo 2 to the power 32. The result is again a signed 32-bit integer. Shift counts use only their lowest five bits, so a shift by 32 is a shift by 0. The run below shows each rule on chosen values. In this course a block that shows one function leaves out the imports and constants at the top of its file, and test and demonstration blocks show their imports.
const show = (label: string, v: number) => console.log(label.padEnd(22), v) show('5 & 3', 5 & 3) show('5 | 3', 5 | 3) show('5 ^ 3', 5 ^ 3) show('~5', ~5) show('1 << 4', 1 << 4) show('-16 >> 2', -16 >> 2) show('-16 >>> 2', -16 >>> 2) show('1 << 31', 1 << 31) show('(1 << 31) >>> 0', (1 << 31) >>> 0) show('1 << 32', 1 << 32) show('2 ** 32 + 5 | 0', 2 ** 32 + 5 | 0) show('2 ** 31 | 0', 2 ** 31 | 0) show('7.9 | 0', 7.9 | 0) show('-7.9 | 0', -7.9 | 0) show('NaN | 0', NaN | 0)
5 & 3 1 5 | 3 7 5 ^ 3 6 ~5 -6 1 << 4 16 -16 >> 2 -4 -16 >>> 2 1073741820 1 << 31 -2147483648 (1 << 31) >>> 0 2147483648 1 << 32 1 2 ** 32 + 5 | 0 5 2 ** 31 | 0 -2147483648 7.9 | 0 7 -7.9 | 0 -7 NaN | 0 0
Read the output as a list of surprises. The number 1 << 31 is negative because the bit that reached position 31 is the sign bit. Adding >>> 0 reinterprets the same 32 bits as an unsigned number, giving 2147483648. A value of 2 ** 32 + 5 becomes 5, because the top part wraps away without any warning. A value such as 7.9 loses its fraction, and NaN becomes 0.
BigInt and the lowest set bit
When a value can pass 32 bits, use BigInt. Its operators &, |, ^, ~, << and >> work on integers of any width, and a literal ends in n. Two limits matter. A BigInt cannot be mixed with a plain number in one expression, and it has no unsigned right shift, because there is no fixed width to shift in from. To wrap a BigInt to 32 bits on purpose, use BigInt.asUintN(32, x) or BigInt.asIntN(32, x).
const wide = 2n ** 40n + 5n console.log(wide & 0xffn, wide >> 38n, wide << 3n) console.log(BigInt.asUintN(32, -1n), BigInt.asIntN(32, 2n ** 31n)) const one: any = 1 try { console.log(1n + one) } catch (e) { console.log((e as Error).name + ': ' + (e as Error).message) } const big: any = 1n const none: any = 0n try { console.log(big >>> none) } catch (e) { console.log((e as Error).name + ': ' + (e as Error).message) }
5n 4n 8796093022248n 4294967295n -2147483648n TypeError: Cannot mix BigInt and other types, use explicit conversions TypeError: BigInts have no unsigned right shift, use >> instead
Now the two identities used all through this chapter. For a positive x, the expression x & (x - 1) clears the lowest set bit. The reason is that subtracting 1 turns the lowest set bit into 0 and turns every zero below it into 1; bits above it do not change. ANDing with x then keeps only the bits above, so the lowest set bit disappears. The expression x & -x keeps only that lowest set bit instead: since -x is ~x + 1, the same borrow pattern leaves the lowest set bit and everything below it equal to x, and flips everything above it, so the AND removes the upper part.
const bin = (x: number) => (x >>> 0).toString(2).padStart(8, '0') for (const x of [44, 64, 7, 0]) { console.log(`x = ${bin(x)}`) console.log(`x & (x - 1) = ${bin(x & (x - 1))}`) console.log(`x & -x = ${bin(x & -x)}`) }
x = 00101100 x & (x - 1) = 00101000 x & -x = 00000100 x = 01000000 x & (x - 1) = 00000000 x & -x = 01000000 x = 00000111 x & (x - 1) = 00000110 x & -x = 00000001 x = 00000000 x & (x - 1) = 00000000 x & -x = 00000000
For 44, which is 00101100, clearing the lowest set bit gives 00101000 and isolating it gives 00000100. For 0 both expressions are 0, so the loops in the next lessons can use "x is not 0" as their stopping test.
Part 2 · The one unpaired sensor id
XOR and why pairs vanish
A warehouse sensor log holds the id of every scanner that reported in. Each scanner reports twice, once going in and once coming out, except one that failed halfway. You need the id of the scanner that reported once. A hash set would work, and so would sorting, but exclusive or solves it with one integer and one pass.
XOR (^) has three properties that make this possible. First, a ^ a is 0: a value cancels itself. Second, a ^ 0 is a: zero changes nothing. Third, XOR is commutative and associative, so the order in which you combine values does not change the result. Together they give a short argument. If you fold a list of ids with XOR, you may regroup the ids freely, so put each pair next to each other. Every pair becomes 0, the zeros vanish, and what remains is the one id without a partner.
Written as a statement to check: if every value in a list appears exactly twice except one value that appears once, the XOR of the whole list equals that value. The argument above is the proof, and the run later in this lesson tests it on 3,000 random lists. The scene shows the fold on five ids. The intermediate values of acc look unrelated to the answer, because 12 and 10 are mixtures. Only after both copies of 9 and both copies of 5 have been folded in do they cancel.
Watch for matching ids cancelling inside acc
Read it as steps
Matching ids cancel, so the unpaired one is left in acc
Three problems, one fold
The same idea answers two close relatives. In the first, a string t is a shuffled copy of string s with one extra character, and you want that character. In the second, an array holds n distinct numbers taken from 0 to n, so exactly one number in that range is missing. Both fit the pattern once you see the right multiset, which is a collection where repeats count.
For the extra character, fold the character codes of both strings. Each character of s appears once in s and once in t, so it cancels. The extra one has no partner. For the missing number, fold every index from 0 to n - 1, every value in the array, and also n. Together that makes every number from 0 to n appear once as an index or n, and every present number appears once more as a value. The missing number appears only once.
export function singleNumber(ids: number[]): number { let acc = 0 for (const id of ids) acc ^= id return acc } // t is s with one extra character, in any position export function extraChar(s: string, t: string): string { let acc = 0 for (const c of s) acc ^= c.codePointAt(0)! for (const c of t) acc ^= c.codePointAt(0)! return String.fromCodePoint(acc) }
The extra-character version uses codePointAt(0) and a for...of loop so that characters outside the basic range, such as emoji, still count as one unit. XOR of values up to 0x10FFFF stays well inside 32 bits.
// nums holds n distinct values taken from 0..n export function missing(nums: number[]): number { let acc = nums.length for (let i = 0; i < nums.length; i++) acc ^= i ^ nums[i] return acc }
A function that returns the right value for typical input is not finished. The tests below cover an empty list, negative ids and the largest missing value.
Tests, a stress run and the 32-bit limit
import test from 'node:test' import assert from 'node:assert/strict' import { singleNumber, extraChar, missing } from './xor.ts' test('unpaired id', () => { assert.equal(singleNumber([41, 7, 90, 7, 41]), 90) assert.equal(singleNumber([]), 0) assert.equal(singleNumber([-5, 3, 3]), -5) }) test('extra character', () => { assert.equal(extraChar('route', 'rotuey'), 'y') assert.equal(extraChar('', 'm'), 'm') }) test('missing number', () => { assert.equal(missing([4, 0, 3, 1]), 2) assert.equal(missing([]), 0) assert.equal(missing([0, 1, 2]), 3) })
✔ unpaired id ✔ extra character ✔ missing number ℹ tests 3 ℹ pass 3 ℹ fail 0
The tests pass, so check the claim at scale. The stress run builds 3,000 random lists with one unpaired id, shuffles them, and compares the fold with the known answer. It does the same for the extra character and the missing number, and it printed this line.
3000 rounds agreeOne limit remains. The XOR operator converts both operands to 32-bit integers first. An id such as 2 32 + 7 therefore looks like 7, and a list where the real unpaired id is 2 32 + 7 returns the wrong value. The run below shows it, then repeats the fold with BigInt, which is exact at any width, using the function above. It also prints the value of acc after each id of the scene.
export function singleNumberBig(ids: bigint[]): bigint { let acc = 0n for (const id of ids) acc ^= id return acc }
import { singleNumber, singleNumberBig } from './xor.ts' const ids = [2 ** 32 + 7, 7, 7] console.log('numbers:', singleNumber(ids)) console.log('bigints:', singleNumberBig(ids.map(BigInt))) let acc = 0 for (const id of [5, 9, 6, 9, 5]) { acc ^= id console.log(`after ${id}: acc = ${acc}`) }
numbers: 7 bigints: 4294967303n after 5: acc = 5 after 9: acc = 12 after 6: acc = 10 after 9: acc = 3 after 5: acc = 6
The first line is wrong and the second is right. When ids are bounded by the 32-bit range, the plain version is correct and fast. When ids can be larger, switch to BigInt or to a Map of counts. The same rule applies in every lesson of this chapter: say the range of the input, and pick the arithmetic that stays exact inside it.
Related on LeetCode: Single Number, Find the Difference and Missing Number.
Part 3 · Counting permission bits
Permissions as one integer
A file store keeps three permissions for each user: read, write and execute. Instead of three booleans, it stores one small integer where each permission owns a bit. Giving a permission is an OR, taking it away is an AND with the inverted flag, and checking it is an AND followed by a comparison.
export const READ = 1 export const WRITE = 2 export const EXEC = 4 export const grant = (mask: number, p: number) => mask | p export const revoke = (mask: number, p: number) => mask & ~p export const has = (mask: number, p: number) => (mask & p) === p export const differing = (a: number, b: number) => popcount(a ^ b)
The has helper compares with the flag itself, not with zero, so it also works when you pass a mask with several bits. The last helper counts how many permissions differ between two users. It needs a way to count set bits, which is the subject of the rest of the lesson. The number of set bits is called the population count or Hamming weight, and the number of positions in which two values differ is their Hamming distance.
The distance follows from XOR. A bit of a ^ b is 1 exactly where a and b disagree, so the Hamming distance is the population count of a ^ b. Counting differing permissions is therefore one XOR and one count.
Counting by clearing the lowest bit
The obvious way to count set bits tests all 32 positions. A faster way uses the identity from the first lesson. Each step x &= x - 1 removes exactly one set bit, so a loop that runs until x is 0 executes once per set bit. The count is the number of steps.
const MAX32 = 0xffffffff export function popcount(x: number): number { if (!Number.isInteger(x) || x < -(2 ** 31) || x > MAX32) throw new RangeError('need an integer that fits in 32 bits') let n = 0 while (x !== 0) { x &= x - 1 n++ } return n } export function popcountBig(x: bigint): number { if (x < 0n) throw new RangeError('need a non-negative value') let n = 0 while (x !== 0n) { x &= x - 1n n++ } return n }
The first line rejects values that do not fit. popcountBig is the same loop on a BigInt, which has no 32-bit limit. Without it, the loop gives silent wrong answers for large numbers, as the run below shows. Negative numbers are fine: -1 is 32 set bits in two's complement, and the loop reaches 0 after 32 steps.
Watch for the lowest set bit vanishing at every step
Read it as steps
Each x & (x - 1) removes exactly one set bit
Here is the same idea on a permission mask. A user with read and execute holds 1 plus 4, which is 5, or 101 in binary. One clearing step turns 101 into 100, and a second turns 100 into 0, so two steps match two permissions. A table of counts, built on the next page, gives the same answer for 5 from the entries before it: the count for 5 is the count for 2 plus the last bit of 5, which is 1 plus 1, or 2.
A table of counts, and the 32-bit edge
Sometimes you need the count for every number from 0 to n, for example to rank all permission sets. Calling the loop for each number works, but there is a shorter relation. Shifting right by one drops the last bit, and the last bit is i & 1. So the count for i is the count for i >> 1 plus that last bit, and the count for i >> 1 is already in the table because it is smaller.
export function countBits(n: number): number[] { if (!Number.isInteger(n) || n < 0 || n > 2 ** 31 - 1) throw new RangeError('need an integer from 0 to 2^31 - 1') const out = [0] for (let i = 1; i <= n; i++) out.push(out[i >> 1] + (i & 1)) return out }
The tests check zero, a small table, the permission helpers and the rejected inputs. The stress run compares the loop, the table and the distance against a string-based count for 5,000 random values and prints one line.
import test from 'node:test' import assert from 'node:assert/strict' import { popcount, popcountBig, countBits } from './bits.ts' import { READ, WRITE, EXEC } from './bits.ts' import { grant, revoke, has, differing } from './bits.ts' test('popcount', () => { assert.equal(popcount(0), 0) assert.equal(popcount(44), 3) assert.equal(popcount(-1), 32) assert.equal(popcount(2 ** 32 - 1), 32) assert.equal(popcount(2 ** 31), 1) assert.throws(() => popcount(2 ** 32 + 1), RangeError) assert.throws(() => popcount(NaN), RangeError) assert.equal(popcountBig(2n ** 32n + 1n), 2) }) test('countBits', () => { assert.deepEqual(countBits(0), [0]) assert.throws(() => countBits(1.5), RangeError) assert.deepEqual(countBits(9), [0, 1, 1, 2, 1, 2, 2, 3, 1, 2]) }) test('permissions', () => { const m = grant(READ, EXEC) assert.ok(has(m, EXEC) && !has(m, WRITE)) assert.equal(revoke(m, READ), EXEC) assert.equal(revoke(0, READ), 0) assert.equal(differing(READ | WRITE, WRITE | EXEC), 2) })
✔ popcount ✔ countBits ✔ permissions ℹ tests 3 ℹ pass 3 ℹ fail 0
popcount, table and distance agree
The demonstration shows the clearing steps for 44, the result for -1 and 2 ** 31, the error for a value that is too wide, and what the loop would have returned without the check.
00101100 00101000 00100000 steps: 3 popcount: 3 32 1 RangeError: need an integer that fits in 32 bits 1 2
The last line is the point: 2 ** 32 + 1 has two set bits, and the loop without a guard reports 1 because the operands are wrapped to 32 bits before the AND. The BigInt version returns 2. The cost of the loop is the number of set bits, at most 32 for numbers in range, and the table costs one step per entry.
Part 4 · Complements and powers of two
Flipping only the significant bits
The complement of a number in everyday terms flips only the bits that matter. For 44, which is 101100, the complement is 010011, which is 19. A plain ~44 gives -45 instead, because it flips all 32 bits, including the leading zeros that no one wrote down.
The fix is to build a mask of ones as long as the number itself and XOR with it. The length of the number in bits is 32 - Math.clz32(n), where Math.clz32 counts leading zero bits. A mask with that many ones is (1 << len) - 1. XOR with the mask flips exactly the significant bits. For 44 the length is 6, the mask is 111111, and 101100 ^ 111111 gives 010011.
Edge cases decide whether this is correct. We choose the convention that the complement of 0 is 1, treating 0 as the one-bit number 0. And the mask for a 32-bit number cannot be (1 << 32) - 1, because a shift by 32 is a shift by 0 and the mask would come out as 0. The same problem appears with 2 ** 31, where 1 << 31 is negative. The function below special-cases a length of 32 and reads the answer as unsigned with >>> 0.
const MAX32 = 0xffffffff // Flip the significant bits of n. Convention: complement(0) is 1. export function complement(n: number): number { if (!Number.isInteger(n) || n < 0 || n > MAX32) throw new RangeError('need an integer from 0 to 2^32 - 1') const len = n === 0 ? 1 : 32 - Math.clz32(n) const mask = len === 32 ? MAX32 : (1 << len) - 1 return (n ^ mask) >>> 0 }
The run below shows why the special case exists. The naive mask for 32 bits is 0, so XOR with it flips nothing, and 1 << 31 is negative.
console.log(1 << 31, 1 << 32) const naiveMask = (1 << 32) - 1 console.log(naiveMask, 2 ** 31 ^ naiveMask)
-2147483648 1 0 -2147483648
Powers of two and the 32-bit trap
const naive = (x: number) => x > 0 && (x & (x - 1)) === 0 console.log(naive(2 ** 40 + 8), naive(2 ** 40), naive(2 ** 31)) console.log(2 ** 40 + 8 & 2 ** 40 + 7, (2 ** 40 + 8) | 0)
true true true 0 8
The first line is true true true, and the first of those is wrong: 2 ** 40 + 8 is not a power of two, but the naive test says it is. The test x & (x - 1) is zero for a positive power of two, because such a number has a single set bit, and clearing it leaves nothing. For a number with more set bits, clearing the lowest one leaves the others behind, so the result is non-zero. That argument is right for 32-bit values. For 2 ** 40 + 8 the operands are wrapped to 32 bits first, the high bit is lost, and what remains is 8, which looks like a power of two.
The safe version rejects anything that is not a whole number above zero and does the test in BigInt, which has no wrapping. Every whole-valued double converts to BigInt exactly, so powers of two such as 2 53 and 2 1023 are also recognised. For rounding a buffer size up to the next power of two, use the leading zero count again: the smallest power of two that is at least x is 1 << (32 - Math.clz32(x - 1)), with 1 as a special case. The shift reaches 2 31 for sizes above 2 30, and a shift to bit 31 is negative, so the function rejects sizes above 2 ** 30.
export function isPowerOfTwo(x: number): boolean { if (!Number.isInteger(x) || x <= 0) return false const b = BigInt(x) return (b & (b - 1n)) === 0n }
// Smallest power of two that is at least x, for 1 <= x <= 2^30. export function roundUp(x: number): number { if (!Number.isInteger(x) || x < 1 || x > 2 ** 30) throw new RangeError('need an integer from 1 to 2^30') return x === 1 ? 1 : 1 << (32 - Math.clz32(x - 1)) }
The second line of the run shows the wrapping: both operands become 8 and 7, and their AND is 0. The tests below cover the edges: 0, 1, 2 ** 31, the largest 32-bit value, negative numbers, NaN, fractions, -0 and a number far above 32 bits.
Tests and a comparison run
import test from 'node:test' import assert from 'node:assert/strict' import { complement, isPowerOfTwo, roundUp } from './mask.ts' test('complement flips only the significant bits', () => { assert.equal(complement(0), 1) assert.equal(complement(1), 0) assert.equal(complement(0b101100), 0b010011) assert.equal(complement(2 ** 31), 2 ** 31 - 1) assert.equal(complement(2 ** 32 - 1), 0) for (const bad of [-1, 2 ** 32, NaN]) assert.throws(() => complement(bad), RangeError) }) test('powers of two', () => { assert.ok(isPowerOfTwo(1) && isPowerOfTwo(4096)) assert.ok(isPowerOfTwo(2 ** 53) && isPowerOfTwo(2 ** 1023)) assert.ok(!isPowerOfTwo(2 ** 40 + 8) && !isPowerOfTwo(2 ** 53 + 2)) assert.ok(!isPowerOfTwo(0) && !isPowerOfTwo(-8)) assert.ok(!isPowerOfTwo(12) && !isPowerOfTwo(-0)) assert.ok(!isPowerOfTwo(NaN) && !isPowerOfTwo(6.5)) }) test('round up to a power of two', () => { const sizes = [1, 2, 3, 4, 5, 1000].map(roundUp) assert.deepEqual(sizes, [1, 2, 4, 4, 8, 1024]) assert.equal(roundUp(2 ** 30), 2 ** 30) assert.throws(() => roundUp(2 ** 30 + 1), RangeError) assert.throws(() => roundUp(0), RangeError) })
✔ complement flips only the significant bits ✔ powers of two ✔ round up to a power of two ℹ tests 3 ℹ pass 3 ℹ fail 0
The comparison run draws 5,000 random numbers of random bit lengths. It checks the complement against a string version that swaps every 0 and 1 in the binary text, checks the power-of-two test against a pattern match on the binary text, and checks that every rounded-up size is a power of two that is at least the input and less than twice it.
complement, power test and round up agree
These helpers appear whenever a size must be a power of two, such as the buckets of a hash table or the length of a ring buffer, because then a bit mask replaces a modulo: i & (size - 1) is i % size when size is a power of two. That identity is the practical reason for the power-of-two test.
Related on LeetCode: Complement of Base 10 Integer and Power of Two.
Why is ~44 not the complement of 44 in the sense of flipping its significant bits?
~flips all 32 bits, including the leading zeros, so it gives -45. The significant-bit complement of 101100 is 010011, which is 19.
Part 5 · Reversing a 32-bit checksum
Packing fields, then reversing them
A device sends a 32-bit status word. Its top 4 bits hold a version, the next 8 a set of flags and the low 20 a length. A checksum routine on the receiving side needs the bits of that word in reverse order. Both jobs are bit manipulation: packing and unpacking a word with shifts and masks, and reversing it.
Packing shifts each field to its place and ORs them together. Unpacking shifts the field down and ANDs with a mask of its width. The word is read as unsigned with >>> 0, because a version of 8 or more sets bit 31.
// layout: version (4 bits) | flags (8 bits) | length (20 bits) const fits = (v: number, limit: number) => Number.isInteger(v) && v >= 0 && v < limit export function pack(version: number, flags: number, length: number) { if (!fits(version, 16) || !fits(flags, 256) || !fits(length, 2 ** 20)) throw new RangeError('field out of range') return ((version << 28) | (flags << 20) | length) >>> 0 } // word: an unsigned 32-bit integer, as pack returns export function unpack(word: number) { return { version: word >>> 28, flags: (word >>> 20) & 0xff, length: word & 0xfffff, } }
const word = pack(9, 0b10100101, 1_000_000) console.log(word, word.toString(2).padStart(32, '0')) console.log(unpack(word)) console.log((9 << 28 | 0xa5 << 20 | 1_000_000))
2589934144 10011010010111110100001001000000 { version: 9, flags: 165, length: 1000000 } -1705033152
The first line is the packed word, which is above 2 ** 31, shown in decimal and in binary. The last line shows the same expression without >>> 0: the result is the negative number -1705033152. It is the same 32 bits, read as signed.
Reversing with a loop
To reverse the bits of x, peel them off from the right and push them onto the result from the left. Each round shifts the result left by one, ORs in the lowest bit of x, and shifts x right. After 32 rounds the lowest bit of the original is the highest bit of the result.
Two details matter in JavaScript. The shift of x must be unsigned, x >>>= 1, so that a value above 2 31 does not drag its sign bit along. And the result must be returned as r >>> 0. Without it, an input of 1 returns -2147483648, because bit 31 is set and the result is signed. The input must be an integer from 0 to 2 32 - 1.
function check(x: number): void { if (!Number.isInteger(x) || x < 0 || x > 0xffffffff) throw new RangeError('need an integer from 0 to 2^32 - 1') }
export function reverseBits(x: number): number { check(x) let r = 0 for (let i = 0; i < 32; i++) { r = (r << 1) | (x & 1) x >>>= 1 } return r >>> 0 }
The demonstration also uses a signed variant, reverseBitsSigned, from the same file. Its loop body is identical, and it returns r as it is, without the final >>> 0.
import { reverseBits, reverseBitsSigned } from './rev.ts' const x = 0b1011 const out = reverseBits(x) console.log(out.toString(2).padStart(32, '0')) console.log(reverseBits(1), reverseBitsSigned(1)) console.log(reverseBits(reverseBits(x)) === x)
11010000000000000000000000000000 2147483648 -2147483648 true
The first line shows 0b1011 reversed: 1101 followed by 28 zeros. The second line shows the unsigned and signed results for input 1: 2147483648 and -2147483648. The third line shows that reversing twice returns the original.
Reversing by swapping blocks
A second method swaps blocks instead of single bits. Swap every pair of adjacent bits, then every pair of adjacent 2-bit blocks, then 4-bit blocks, 8-bit blocks and finally the two 16-bit halves. After the five rounds every bit has moved to the mirror position. Each round uses a mask that selects alternate blocks: 0x55555555 selects every other bit, 0x33333333 every other pair, and so on.
Why it works: consider a bit at position p. Round k swaps adjacent blocks of 2 to the power k bits, which moves a bit from position p to the position where bit k of p is flipped. After rounds 0 to 4 all five bits of the position number have been flipped, and flipping all five bits of a number from 0 to 31 gives 31 minus that number, the mirror position. The method needs 5 steps instead of 32 loop rounds.
export function reverseBitsSwap(x: number): number { check(x) x = ((x >>> 1) & 0x55555555) | ((x & 0x55555555) << 1) x = ((x >>> 2) & 0x33333333) | ((x & 0x33333333) << 2) x = ((x >>> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4) x = ((x >>> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8) return ((x >>> 16) | (x << 16)) >>> 0 }
The stress run compares both methods with a string-based reversal for 1,00,000 random values, after trying the edge values 0, 1, 2, 2 31 - 1, 2 31, 2 32 - 2 and 2 32 - 1 first.
100000 values agree with the string versionSpeed is the other reason to know the second method. The run below reverses 20 lakh values with each method and prints a checksum so that the work cannot be skipped. The times are from one run on this machine and they vary between runs; in four runs here the loop took between about 1.5 and 2.1 times as long as the swap method.
import { reverseBits, reverseBitsSwap } from './rev.ts' const n = 2_000_000 const values = Array.from( { length: n }, (_, i) => (i * 2654435761) % 2 ** 32, ) const methods = [ ['loop', reverseBits], ['swap', reverseBitsSwap], ] as const for (const [name, f] of methods) { const t = performance.now() let sum = 0 for (const v of values) sum = (sum + f(v)) % 1000003 const ms = Math.round(performance.now() - t) console.log(name, ms, 'ms for', n, 'values, checksum', sum) }
loop 86 ms for 2000000 values, checksum 208308 swap 41 ms for 2000000 values, checksum 208308
The identical checksums confirm that both methods agree on these values. The gap is expected, since the loop does 32 rounds of three operations and the swap method does five rounds of about six.
Part 6 · The one id seen once among triples
Counting bits modulo 3
A parking system logs a vehicle pass every time a car crosses a gate. A stuck sensor made a mess: every vehicle id was logged exactly three times except one id, which appears once. XOR does not help, because three equal values do not cancel: a ^ a ^ a is a. But counting bits does.
Look at one bit position across the whole list. A vehicle that appears three times adds 3 to the count of ones at that position if its bit is 1, and 0 otherwise. So every repeated vehicle contributes a multiple of 3. The single vehicle contributes 1 if its bit is 1. Therefore the count of ones at the position, taken modulo 3, equals the bit of the single vehicle. Do this for all 32 positions and assemble the answer with OR.
Negative ids need no special care. A negative number in two's complement has its top bit set, and the loop covers position 31 like any other. Building the result with out |= 1 << bit gives a signed 32-bit value, which is exactly what a negative id is. The price is the input range: every id must fit in a signed 32-bit integer, so the function rejects anything else.
export function singleOfThree(ids: number[]): number { for (const id of ids) if (!Number.isInteger(id) || id < -(2 ** 31) || id >= 2 ** 31) throw new RangeError('ids must fit in a signed 32-bit integer') let out = 0 for (let bit = 0; bit < 32; bit++) { let ones = 0 for (const id of ids) ones += (id >>> bit) & 1 if (ones % 3 === 1) out |= 1 << bit } return out }
Checked against counting with a Map
The function takes 32 passes over the list, so it costs 32 times n steps and constant extra space. A Map of counts takes one pass and space for every distinct id. For 3,000 random lists, including ids spread across the full signed 32-bit range and ids with the top bit set, the two agree. The tests cover a single element, a negative id, the smallest 32-bit value and the two kinds of bad input.
import test from 'node:test' import assert from 'node:assert/strict' import { singleOfThree, subsetXorSum } from './triple.ts' test('the id seen once among triples', () => { assert.equal(singleOfThree([8, 8, 31, 8, 31, 31, 6]), 6) assert.equal(singleOfThree([-9, 5, 5, 5]), -9) const low = -(2 ** 31) assert.equal(singleOfThree([7, -3, -3, -3, 7, 7, low]), low) assert.equal(singleOfThree([4]), 4) assert.throws(() => singleOfThree([2 ** 31]), RangeError) assert.throws(() => singleOfThree([1.5]), RangeError) }) test('subset xor totals', () => { assert.equal(subsetXorSum([]), 0) assert.equal(subsetXorSum([6]), 6) assert.throws(() => subsetXorSum([2 ** 31]), RangeError) assert.throws(() => subsetXorSum([-1]), RangeError) assert.throws(() => subsetXorSum([1.5]), RangeError) const wide = Array(24).fill(2 ** 31 - 1) assert.throws(() => subsetXorSum(wide), RangeError) assert.equal(subsetXorSum([2, 8, 3]), 44) })
✔ the id seen once among triples ✔ subset xor totals ℹ tests 2 ℹ pass 2 ℹ fail 0
3000 rounds agree 5 << 30 = 1073741824 5 * 2 ** 30 = 5368709120
The check also compared the formula of the next page with a brute force, and printed the shift comparison that page discusses.
The XOR total of every subset
A related question: take every subset of a list of non-negative numbers, XOR the members of each subset, and add up those results. The empty subset counts as 0. For a list of n numbers there are 2 to the power n subsets, so trying them all is not an option beyond about twenty numbers. A formula does it in one pass.
Argument: look at one bit position. If no number has that bit, it is 0 in every subset XOR and adds nothing. If at least one number has it, split the subsets by whether they contain that number. Adding or removing that one number toggles the bit of the subset XOR, so exactly half of the 2 to the power n subsets have the bit set. The bit therefore contributes its place value times 2 to the power n - 1. Summing over all bits, the total is the OR of all the numbers times 2 to the power n - 1.
// Sum of the XOR of every subset (the empty subset counts as 0). export function subsetXorSum(xs: number[]): number { if (xs.length === 0) return 0 let all = 0 for (const x of xs) { if (!Number.isInteger(x) || x < 0 || x >= 2 ** 31) throw new RangeError('need integers from 0 to 2^31 - 1') all |= x } const total = all * 2 ** (xs.length - 1) if (!Number.isSafeInteger(total)) throw new RangeError('total too large, use BigInt') return total }
Why the formula avoids a shift
The code uses 2 ** (n - 1) and not << (n - 1). A shift would be wrapped to 32 bits and give a wrong answer for larger lists, as the stress run showed in its last line: 5 << 30 is 1073741824, while 5 * 2 ** 30 is 5368709120. The function accepts whole numbers from 0 to 2 31 - 1. With up to 23 entries the product is below 2 53 and exact; for more entries it throws a RangeError, and BigInt is the way out. The same stress run compared the formula with a brute force over every subset for lists of up to 12 numbers, and it agreed in all 3,000 rounds. The empty list returns 0 at once: its only subset is the empty one, whose total is 0.
Related on LeetCode: Single Number II and Sum of All Subset XOR Totals.
Why does XOR fail when every id appears three times except one?
- Three equal values XOR to the value itself, so repeated ids do not cancel. A fold would return the XOR of all distinct ids, not the single one.
- Counting ones per bit position modulo 3 works instead.
For the list [8, 8, 31, 8, 31, 31, 6], what is the count of ones at the bit of value 8, and what does that tell you?
- Three values of 8 and three of 31 have that bit, and 6 does not, so the count is 6 and 6 mod 3 is 0: the single id has this bit clear.
- The single id is 6, which is 00110, and the answer matches the test.
Why is the sum of all subset XORs the OR of the numbers times 2 ** (n - 1)?
- A bit that appears in at least one number is set in exactly half of the 2 n subset XORs, so it adds its place value times 2 (n - 1). A bit in no number adds nothing.
- The OR collects the bits that appear in at least one number.
All chapters · Previous: Custom Data Structures: Composing Maps, Lists and Arrays