SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 4
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 4 of 30

Number questions IV

decimal to binary and back (toString(2), parseInt)count set bitspower of two with n & (n - 1); 32-bit bitwise operators

These are the notes for JavaScript Coding Questions, episode 4, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Three questions about numbers in binary: convert a number to binary and back, count its set bits, and check whether it is a power of two in one line. Along the way, the trap inside every JavaScript bitwise operator: they all work on 32 signed bits, so 2 ** 31 >> 1 is negative and 2 ** 32 + 2 "is" a power of two.

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.

Binary in one picture: a row of light bulbs

Each bit (binary digit) is a bulb that is on (1) or off (0). From the right, the bulbs are worth 1, 2, 4, 8, 16...: each is worth double the one to its right (powers of two). A number is the sum of the lit bulbs:

bulb value:   8   4   2   1
5         =   0   1   0   1    → 4 + 1      = 5    → "101"
10        =   1   0   1   0    → 8 + 2      = 10   → "1010"
255       =   1111 1111        → 128 + ... + 1     → "11111111"

Base (or radix) is how many digits a number system has: 10 for decimal (0-9), 2 for binary (0-1), 16 for hexadecimal (0-9 and a-f), 8 for octal.

Q1: Convert decimal to binary, and back

Problem. Write toBinary(n) that returns the bits of a whole number as a string, and fromBinary(s) that turns a string of bits back into a number. Handle 0 and negative numbers.

Think out loud

  • To binary (the school method): divide by 2 again and again and write down the remainders; read them from the bottom up.
10 ÷ 2 = 5  remainder 0
 5 ÷ 2 = 2  remainder 1
 2 ÷ 2 = 1  remainder 0
 1 ÷ 2 = 0  remainder 1     → read upward: 1010
  • Back to decimal: start at 0; for each bit, double the value and add the bit: "1010" → 1 → 2 → 5 → 10.
  • Edge cases: 0, a negative number, and a string with a digit that isn't 0 or 1.

The obvious attempt

function toBinary(n) {
  let bits = "";
  while (n > 0) {
    bits = (n % 2) + bits;
    n = Math.floor(n / 2);
  }
  return bits;
}
for (const n of [5, 10, 255, 0, -5]) console.log(n, JSON.stringify(toBinary(n)));

Output:

5 "101"
10 "1010"
255 "11111111"
0 ""
-5 ""

JSON.stringify puts quotes around a string, so an empty string shows up as "" instead of a blank.

Why it fails. For 0 and -5 the condition n > 0 is false at the start, so the loop never runs and the empty starting string is returned. (The same edge case as reversing a number in episode 1.)

The fix

function toBinary(n) {
  if (n === 0) return "0";
  const sign = n < 0 ? "-" : "";
  n = Math.abs(n);
  let bits = "";
  while (n > 0) {
    bits = (n % 2) + bits;
    n = Math.floor(n / 2);
  }
  return sign + bits;
}
function fromBinary(s) {
  let value = 0;
  for (const ch of s) value = value * 2 + Number(ch);
  return value;
}
for (const n of [5, 10, 255, 0, -5]) console.log(n, toBinary(n), (n).toString(2));
console.log(fromBinary("1010"), fromBinary("11111111"), parseInt("1010", 2));

Output:

5 101 101
10 1010 1010
255 11111111 11111111
0 0 0
-5 -101 -101
10 255 10

Our function now agrees with the built-in toString(2) on every row, including -101 for -5 (the built-in also writes a minus sign; it does not show the 32-bit two's complement form, see Q2).

Complexity. A number n has about log₂ n bits, and each step removes one: O(log n) time, and O(log n) space for the string.

The built-ins: toString(radix) and parseInt(string, radix)

  • n.toString(2) writes n in base 2 (any base from 2 to 36 works).
  • parseInt(s, 2) reads s as base 2.
  • Number("0b1010") reads the 0b binary prefix (0x for hex, 0o for octal).
console.log(parseInt("1010", 2), parseInt("102", 2), parseInt("2", 2));
console.log(Number("0b1010"), (255).toString(16), parseInt("ff", 16));

Output:

10 2 NaN
10 ff 255

The parseInt trap. parseInt reads digits until it meets one that isn't valid in that base, and quietly stops there: "102" is read as "10", which is 2. If the very first character is invalid, the result is NaN (Not a Number). No error is thrown either way. Validate first if the input matters:

const isBinary = s => /^[01]+$/.test(s);
for (const s of ["1010", "102", "", "0b11"]) console.log(JSON.stringify(s), isBinary(s), isBinary(s) ? parseInt(s, 2) : null);
console.log(parseInt("11111111111111111111111111111111111111111111111111111111", 2));
console.log(BigInt("0b" + "1".repeat(56)));
"1010" true 10
"102" false null
"" false null
"0b11" false null
72057594037927940
72057594037927935n

The regular expression /^[01]+$/ means "from start (^) to end ($), one or more (+) of the characters 0 or 1". The last two lines show another limit: 56 ones is 2⁵⁶ - 1, past Number.MAX_SAFE_INTEGER (episode 3), so parseInt rounds it; BigInt("0b...") is exact.

The literal trap.

console.log(5.toString(2));
.../main.js:1
console.log(5.toString(2));
            ^^

SyntaxError: Invalid or unexpected token

JavaScript reads 5. as the start of a decimal number (like 5.5) and then finds letters. Write (5).toString(2), 5..toString(2) or use a variable.

Bitwise operators

Bitwise operators work on the bits of numbers directly. For each bit position:

Operator Name Rule Example Result
a & b AND 1 if both bits are 1 5 & 3 (101 & 011) 1 (001)
a \| b OR 1 if either bit is 1 5 \| 3 7 (111)
a ^ b XOR 1 if the bits differ 5 ^ 3 6 (110)
~a NOT flips every bit ~5 -6
a << k left shift moves bits left, fills 0s (× 2ᵏ) 5 << 1 10
a >> k signed right shift moves bits right, copies the sign bit 5 >> 1, -5 >> 1 2, -3
a >>> k unsigned right shift moves bits right, fills 0s -5 >>> 28 15
console.log(5 & 3, 5 | 3, 5 ^ 3, ~5, 5 << 1, 5 >> 1, -5 >> 1, -5 >>> 28);
console.log(1.9 | 0, -1.9 | 0, 2 ** 31 | 0, "12" & 6, null | 0, undefined | 0);
1 7 6 -6 10 2 -3 15
1 -1 -2147483648 4 0 0

The second line shows what every bitwise operator does first: it converts its operands to 32-bit signed integers. Decimals are cut off (1.9 | 0 is 1, -1.9 | 0 is -1), 2 ** 31 wraps to -2147483648, strings are converted ("12" & 6 is 4), and null and undefined become 0.

Common uses: n & 1 is the last bit (1 if odd), n >> 1 drops the last bit (halving), 1 << k is 2ᵏ (only up to k = 30 as a positive number), n & (n - 1) turns off the lowest set bit (Q2).

Q2: Count the set bits of n

Problem. A set bit is a bit that is 1. Return how many set bits n has. 5 (101) → 2, 7 (111) → 3, 8 (1000) → 1. This count is also called the popcount or Hamming weight.

Think out loud

  • Look at the last bit with n & 1, then drop it with n >> 1, until nothing is left.
  • Edge cases: 0, 2³¹ (exactly the 32nd bit), -1, a number with more than 32 bits.

The obvious attempt

function countBits(n) {
  let count = 0;
  while (n > 0) {
    count += n & 1;
    n = n >> 1;
  }
  return count;
}
for (const n of [5, 7, 8, 255, 0]) console.log(n, countBits(n));
console.log("2**31:", countBits(2 ** 31), " -1:", countBits(-1), " 2**32+1:", countBits(2 ** 32 + 1));

Output:

5 2
7 3
8 1
255 8
0 0
2**31: 0  -1: 0  2**32+1: 1

The small tests are right. But 2³¹ has one set bit (we got 0), -1 has 32 in its 32-bit form (we got 0), and 2³² + 1 has two (we got 1). No error, just wrong counts.

Why: the 32-bit squeeze

console.log(2 ** 31 >> 1, 2 ** 31 >>> 1);
console.log(-1 >> 1, -1 >>> 1);
console.log((2 ** 32 + 1) & 1, (2 ** 32 + 1) >> 1);
console.log((5 >>> 0).toString(2).padStart(32, "0"));
console.log((-1 >>> 0).toString(2));
console.log((-5 >>> 0).toString(2));

Output:

-1073741824 1073741824
-1 2147483647
1 0
00000000000000000000000000000101
11111111111111111111111111111111
11111111111111111111111111111011
  • Every bitwise operator first squeezes the number into 32 bits, signed. Signed means the leftmost of the 32 bits is the sign bit: if it is 1, the number is negative.
  • 2³¹ is exactly that leftmost bit, so it becomes -2147483648 before the shift, and >> 1 keeps the sign: -1073741824. The loop condition n > 0 then stops at once.
  • 2³² + 1 needs 33 bits; the top bit is simply cut off, so the operators only see 1.
  • Two's complement is how negative numbers are stored. Real-life picture: a car's odometer rolled back from 00000 shows 99999, "one before zero". In 32 bits, -1 is 32 ones, -5 is ...11111011. To negate x: flip every bit and add 1 (~x + 1).
  • >>> (unsigned right shift) reads the 32 bits as a plain counter with no sign and fills zeros from the left. x >>> 0 is the usual way to see a number's 32 bits as an unsigned value.
Fact Example Result
Range of a 32-bit signed integer -2³¹ to 2³¹ - 1 -2147483648 to 2147483647
Range of >>> 0 0 to 2³² - 1 0 to 4294967295
Shift counts are taken mod 32 1 << 32 1 (not 2³²!)
1 << 31 the sign bit -2147483648

Brian Kernighan's trick: n & (n - 1)

Subtracting 1 flips the lowest set bit to 0 and every 0 after it to 1, leaving everything to its left alone. AND-ing with the original then turns off just the lowest set bit:

n         = 12 = 1100
n - 1     = 11 = 1011
n & (n-1) =  8 = 1000      (the lowest lit bulb is off)
then  8 & 7 = 1000 & 0111 = 0   → 2 steps = 2 set bits
function countBits(n) {
  let count = 0;
  while (n !== 0) {
    n &= n - 1;
    count++;
  }
  return count;
}
for (const n of [5, 7, 8, 255, 0, 2 ** 31, -1]) console.log(n, countBits(n));
const big = 2 ** 32 + 1;
console.log(big.toString(2));
console.log(big.toString(2).replaceAll("0", "").length);

Output:

5 2
7 3
8 1
255 8
0 0
2147483648 1
-1 32
100000000000000000000000000000001
2
  • The condition is n !== 0, not n > 0: negative 32-bit numbers have set bits too.
  • 2³¹ → 1 and -1 → 32 are right for the 32-bit form.
  • For numbers past 32 bits, count the 1s in toString(2) (that works for any safe Number), or use BigInt, where & uses every bit:
function countBitsBig(n) {
  let b = BigInt(n), count = 0;
  if (b < 0n) throw new RangeError("negative BigInt has infinitely many 1 bits");
  while (b !== 0n) { b &= b - 1n; count++; }
  return count;
}
console.log(countBitsBig(2 ** 32 + 1), countBitsBig(2n ** 100n - 1n), countBitsBig(0));
2 100 0

(A negative BigInt behaves like two's complement with infinitely many sign bits, so Kernighan's loop would never end on it: hence the check.)

Complexity

Version Time Space
n & 1, >>> 1 until 0 O(32) = O(1) for 32-bit, i.e. one step per bit O(1)
Kernighan n &= n - 1 O(number of set bits) O(1)
Count "1"s in toString(2) O(number of digits) O(digits) for the string

Q3: Is n a power of two?

Problem. Return true if n is 1, 2, 4, 8, 16, ... (2ᵏ for some whole k ≥ 0), otherwise false. 6, 0 and -8 are not.

Real life. Memory sizes (1024 bytes), image sizes for textures (512 × 512), and hash table sizes are powers of two, so this check appears in real code.

Think out loud

  • In binary, a power of two has exactly one bulb on: 8 = 1000, 1024 = 10000000000. 6 = 110 has two.
  • Edge cases: 0 (no bulbs on), negatives, very big numbers (2⁵⁰ + 1, 2³² + 2).

The obvious attempt: Math.log2

const isPowerOfTwo = n => Number.isInteger(Math.log2(n));
for (const n of [1, 2, 8, 6, 1024, 0, -8]) console.log(n, isPowerOfTwo(n));
console.log(2 ** 50 + 1, isPowerOfTwo(2 ** 50 + 1));

Output:

1 true
2 true
8 true
6 false
1024 true
0 false
-8 false
1125899906842625 true

2⁵⁰ + 1 is odd, so it can't be a power of two, yet the answer is true.

Why. Its log₂ is 50.00000000000000128..., but a Number keeps only about 16 significant digits, so the result rounds to exactly 50:

console.log(Math.log2(8), Math.log2(1 << 29), Math.log2(2 ** 50 + 1), Math.log2(0), Math.log2(-8));
console.log(Number.isInteger(Math.log2(2 ** 50 + 1)));
3 29 50 -Infinity NaN
true

Floating-point maths is the wrong tool for an exact yes/no question.

The bit way

A power of two has exactly one set bit, and n & (n - 1) turns off the lowest set bit, so for a power of two the result is 0. n > 0 rules out 0 and negatives.

const isPowerOfTwo = n => n > 0 && (n & (n - 1)) === 0;
for (const n of [1, 2, 8, 6, 1024, 0, -8, 2 ** 30, 2 ** 31]) console.log(n, isPowerOfTwo(n));
console.log(2 ** 32 + 2, isPowerOfTwo(2 ** 32 + 2));

Output:

1 true
2 true
8 true
6 false
1024 true
0 false
-8 false
1073741824 true
2147483648 true
4294967298 true

Note the brackets: === binds tighter than &, so n & (n - 1) === 0 without brackets would mean n & ((n - 1) === 0).

All nine small tests are right, but 2³² + 2 says true. The 32-bit squeeze again: it loses its top bit and becomes just 2.

The fix for any size: BigInt

function isPowerOfTwo(n) {
  const b = BigInt(n);
  return b > 0n && (b & (b - 1n)) === 0n;
}
for (const n of [1, 6, 1024, 0, -8, 2 ** 31, 2 ** 32 + 2, 2 ** 50]) console.log(n, isPowerOfTwo(n));
console.log(isPowerOfTwo(2 ** 50 + 1));

Output:

1 true
6 false
1024 true
0 false
-8 false
2147483648 true
4294967298 false
1125899906842624 true
false

BigInt bitwise operators use every bit, so the answer is right at any size. Time O(1) for normal-sized numbers (the BigInt operations grow with the number of bits), space O(1). For 32-bit inputs, the one-liner with Numbers is the classic interview answer; mention the 32-bit limit and the BigInt version.

Complexity summary

Question Approach Time Extra space
To binary divide by 2 O(log n) O(log n) string
From binary value × 2 + bit O(length) O(1)
Count set bits n & 1, shift O(bits) O(1)
Count set bits Kernighan n &= n - 1 O(set bits) O(1)
Power of two Math.log2 O(1), but wrong for big n O(1)
Power of two n > 0 && (n & (n - 1)) === 0 O(1), 32-bit only O(1)
Power of two the same with BigInt O(bits), any size O(1)

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
Forgetting 0 and negatives while (n > 0) in toBinary 0 → "", -5 → "" the loop never runs return "0"; keep the sign
Trusting parseInt parseInt("102", 2) 2 stops at the first bad digit validate with /^[01]+$/
Bad first digit parseInt("2", 2) NaN no valid digit at all validate first
Method on a number literal 5.toString(2) SyntaxError: Invalid or unexpected token 5. starts a decimal (5).toString(2)
>> on 2³¹ or more 2 ** 31 >> 1 -1073741824 bitwise is 32-bit signed >>>, or BigInt
Loop with n > 0 on negatives countBits(-1) 0 negatives have set bits while (n !== 0) with &=
Numbers past 32 bits countBits(2 ** 32 + 1) 1 the 33rd bit is cut off toString(2) or BigInt
Shifting by 32 1 << 32 1 shift counts are mod 32 2 ** 32, or BigInt 1n << 32n
Floating-point log Number.isInteger(Math.log2(n)) 2 ** 50 + 1 → true the log is rounded n & (n - 1)
Missing brackets n & n - 1 === 0 wrong answers === binds tighter than & (n & (n - 1)) === 0

Mini project: file permission flags

Bit flags store several yes/no settings in one number, like Linux file permissions (rwx: read, write, execute). This is exactly how chmod 755 works: 7 = 111 = rwx, 5 = 101 = r-x.

const READ = 1 << 2, WRITE = 1 << 1, EXEC = 1 << 0;   // 4, 2, 1
function describe(p) {
  return (p & READ ? "r" : "-") + (p & WRITE ? "w" : "-") + (p & EXEC ? "x" : "-");
}
let perms = READ | WRITE;
console.log(perms, describe(perms));
perms |= EXEC;
console.log(perms, describe(perms));
perms &= ~WRITE;
console.log(perms, describe(perms));
perms ^= READ;
console.log(perms, describe(perms));
console.log([7, 5, 4, 0].map(describe).join(" "));
6 rw-
7 rwx
5 r-x
1 --x
rwx r-x r-- ---
  • |= with a flag turns it on, &= ~flag turns it off, ^= toggles it, and p & flag tests it.
  • Extend it: parse a string like "rwxr-xr--" into three numbers (owner, group, others) and print 754.

Your turn: bits to flip to turn a into b (solution)

Problem. How many bits must you flip to turn a into b? a = 10 (1010), b = 7 (0111) → 3.

Solution

a ^ b has a 1 exactly where a and b differ. Count its set bits with Kernighan's loop:

function countBits(n) {
  let count = 0;
  while (n !== 0) { n &= n - 1; count++; }
  return count;
}
const bitsToFlip = (a, b) => countBits(a ^ b);
console.log(bitsToFlip(10, 7), bitsToFlip(0, 255), bitsToFlip(5, 5), bitsToFlip(-1, 0));
console.log((10 ^ 7).toString(2));
3 8 0 32
1101

Check: 1101 has three 1s: positions 3, 2 and 0, exactly the three bits where 1010 and 0111 differ. This count is called the Hamming distance. Time O(set bits of a ^ b), space O(1). For numbers past 32 bits, do the same with BigInt.

Practice questions (with solutions)

1. Is the k-th bit of n set? (bit 0 is the rightmost)

Solution
const isBitSet = (n, k) => ((n >> k) & 1) === 1;
console.log(isBitSet(5, 0), isBitSet(5, 1), isBitSet(5, 2), isBitSet(-1, 31));
console.log(5 | (1 << 1), 7 & ~(1 << 1), 5 ^ (1 << 0));
console.log(1 << 31, 1 << 32);
true false true true
7 5 4
-2147483648 1

Shift the bit you want to position 0 and test it. The second line sets bit 1 of 5 (→ 7), clears bit 1 of 7 (→ 5), and toggles bit 0 of 5 (→ 4). The last line shows the limits: 1 << 31 is the sign bit, and 1 << 32 is 1 because the shift count is taken mod 32.

2. Swap two numbers with XOR (and why it's a bad idea).

Solution
let a = 3, b = 9;
a ^= b; b ^= a; a ^= b;
console.log(a, b);
const arr = [4];
let i = 0, j = 0;
arr[i] ^= arr[j]; arr[j] ^= arr[i]; arr[i] ^= arr[j];
console.log(arr);
let x = 3, y = 9;
[x, y] = [y, x];
console.log(x, y);
9 3
[ 0 ]
9 3

It works because x ^ x = 0 and x ^ 0 = x. But when both "variables" are the same place (i === j), the first step sets it to 0 and the value is lost: [ 4 ] became [ 0 ]. It also only works on 32-bit integers. In JavaScript, swap with destructuring: [x, y] = [y, x]. Interviewers ask this to see whether you know the trap.

3. Every number appears twice except one. Find it, in O(n) time and O(1) space.

Solution

XOR all of them: pairs cancel (x ^ x = 0) and the order doesn't matter, so only the single one is left.

function singleNumber(nums) {
  let result = 0;
  for (const x of nums) result ^= x;
  return result;
}
console.log(singleNumber([4, 1, 2, 1, 2]), singleNumber([7]), singleNumber([-3, 5, 5]));
4 7 -3

4. Convert to any base from 2 to 36 by hand (and compare with toString(base)).

Solution
function toBase(n, base) {
  const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  if (n === 0) return "0";
  let s = "", sign = n < 0 ? "-" : "";
  n = Math.abs(n);
  while (n > 0) { s = digits[n % base] + s; n = Math.floor(n / base); }
  return sign + s;
}
for (const [n, b] of [[255, 16], [255, 8], [10, 2], [-42, 3], [35, 36]]) console.log(n, b, toBase(n, b), n.toString(b));
255 16 ff ff
255 8 377 377
10 2 1010 1010
-42 3 -1120 -1120
35 36 z z

The same divide-and-collect-remainders method, with a digit table for digits above 9.

5. The smallest power of two ≥ n.

Solution
function nextPowerOfTwo(n) {
  if (n <= 1) return 1;
  let p = 1;
  while (p < n) p *= 2;
  return p;
}
for (const n of [0, 1, 5, 8, 9, 1000, 2 ** 40 + 1]) console.log(n, nextPowerOfTwo(n));
0 1
1 1
5 8
8 8
9 16
1000 1024
1099511627777 2199023255552

Multiplying by 2 (not p <<= 1) keeps it correct past 32 bits. O(log n) time.

Quick quiz

1. (From the video.) What does this print?

console.log(6 & 3, 6 | 3, 6 ^ 3);

(A) 2 7 5 (B) 9 9 3 (C) 2 7 3 (D) 1 8 5

Answer

(A) 2 7 5. 6 is 110 and 3 is 011. AND keeps the bit both have: 010 = 2. OR keeps every bit either has: 111 = 7. XOR keeps the bits that differ: 101 = 5.

2. What does console.log(~0, ~-1, ~~3.7) print?

Answer
-1 0 3

~x is -x - 1 in two's complement. ~~x flips twice, which just converts to a 32-bit integer, cutting off the decimals (an old trick for Math.trunc that breaks past 2³¹).

3. What is parseInt("1012", 2)?

Answer

5: it reads "101" and stops at the 2.

4. What does 1 << 33 give?

Answer

2: shift counts are taken mod 32, so it is 1 << 1.

Interview questions

  1. How do you convert a number to binary in JavaScript? n.toString(2); by hand, divide by 2 and collect the remainders in reverse. Back: parseInt(s, 2) or Number("0b" + s).
  2. What do the bitwise operators do to their operands first? Convert them to 32-bit signed integers (>>> gives an unsigned result). Decimals are cut off and numbers past 32 bits lose their top bits.
  3. What is two's complement? The way computers store negative integers: -x is ~x + 1. In 32 bits, -1 is all ones and the top bit is the sign.
  4. What is the difference between >> and >>>? >> copies the sign bit in from the left (keeps negatives negative); >>> fills zeros (treats the bits as unsigned).
  5. Explain n & (n - 1). It clears the lowest set bit. Uses: count set bits in O(set bits), check a power of two (result 0 and n > 0).
  6. How do you check if a number is a power of two? n > 0 && (n & (n - 1)) === 0, valid for 32-bit values; use BigInt beyond that. Not Math.log2: it rounds.
  7. Why is Number.isInteger(Math.log2(n)) wrong for 2⁵⁰ + 1? The exact log is 50.0000000000000013, which can't be stored in a double, so it rounds to 50.
  8. How do you find the single non-duplicate number in O(1) space? XOR all elements; pairs cancel.
  9. How many bits differ between a and b? The popcount of a ^ b (Hamming distance).
  10. What are bit flags? Several booleans packed into one number, one bit each: set with |, clear with & ~, toggle with ^, test with &. Examples: file permissions, feature flags.

Glossary

Term Meaning Example
Bit A binary digit: 0 or 1 the last bit of 5 is 1
Binary Base 2: numbers written with only 0 and 1 5 is 101
Base / radix How many digits a number system uses 2, 8, 10, 16
Decimal Base 10, the everyday system 255
Hexadecimal Base 16: digits 0-9 and a-f 255 is ff
Place value What a digit position is worth; in binary, powers of two 8, 4, 2, 1
Power of two 2ᵏ for a whole k ≥ 0 1, 2, 4, 1024
toString(radix) Writes a number in a given base (255).toString(16) is "ff"
parseInt(s, radix) Reads a string as a number in a given base; stops at the first invalid digit parseInt("102", 2) is 2
NaN "Not a Number": the result of an impossible numeric operation parseInt("2", 2)
0b prefix Marks a binary literal or string 0b1010 is 10
JSON.stringify Turns a value into JSON text; shows quotes around strings JSON.stringify("") is '""'
Regular expression A pattern for matching text /^[01]+$/
SyntaxError The code can't be parsed 5.toString(2)
Bitwise operator An operator that works on individual bits & \| ^ ~ << >> >>>
AND (&) 1 where both bits are 1 6 & 3 is 2
OR (\|) 1 where either bit is 1 6 \| 3 is 7
XOR (^) 1 where the bits differ 6 ^ 3 is 5
NOT (~) Flips every bit ~5 is -6
Left shift (<<) Moves bits left, filling zeros: × 2ᵏ 5 << 1 is 10
Signed right shift (>>) Moves bits right, copying the sign bit -5 >> 1 is -3
Unsigned right shift (>>>) Moves bits right, filling zeros -1 >>> 1 is 2147483647
32-bit signed integer A whole number stored in 32 bits, top bit = sign: -2³¹ to 2³¹ - 1 what \|, &, >> work on
Sign bit The leftmost bit; 1 means negative 1 << 31 is -2147483648
Two's complement Negative numbers stored as ~x + 1; -1 is all ones (-1 >>> 0).toString(2)
Set bit A bit that is 1 7 has three
Popcount / Hamming weight The number of set bits popcount(255) = 8
Hamming distance The number of bit positions where two numbers differ popcount(a ^ b)
Brian Kernighan's trick n & (n - 1) clears the lowest set bit 12 → 8
Bit flag One bit used as a yes/no setting READ = 1 << 2
Bit mask A number used to pick out bits perms & WRITE
BigInt bitwise & \| ^ ~ << >> on BigInts use every bit (no >>>) 2n ** 100n - 1n
Floating-point rounding A double keeps about 16 significant digits Math.log2(2 ** 50 + 1) is 50
O(log n) Steps grow with the number of digits/bits toBinary
O(1) A fixed amount of work the power of two check

Summary

  • Binary is a row of bulbs worth 1, 2, 4, 8...; convert by dividing by 2 and reading the remainders upward; back with value * 2 + bit. Handle 0 and the sign.
  • toString(2) and parseInt(s, 2) do it for you, but parseInt stops quietly at a bad digit ("102" → 2, "2" → NaN); validate with /^[01]+$/. Write (5).toString(2).
  • Every bitwise operator works on 32 signed bits: decimals are cut, bits past 32 are lost, 2³¹ turns negative, and 1 << 32 is 1. Negative numbers are two's complement: -1 is 32 ones. >>> reads the bits as unsigned.
  • n & (n - 1) clears the lowest set bit: count set bits in O(set bits), and n > 0 && (n & (n - 1)) === 0 checks a power of two in O(1).
  • Math.log2 rounds: 2 ** 50 + 1 came out a "power of two". Past 32 bits, use BigInt or toString(2).

Next episode: Array questions I: the largest and second largest (with duplicates), min and max in one pass, and why Math.max(...arr) crashes on 200,000 items.