· By John Kavanagh

JavaScript Numbers in Algorithm Problems

Number and arithmetic keys on a vintage desk calculator.
Image by Ben Wicks, licensed from Unsplash.

An algorithm can have the right recurrence, visit every element once, and still return the wrong integer. JavaScript won't necessarily throw or print anything suspicious. It may simply produce a perfectly respectable‑looking answer that happens to be one out.

Before choosing a loop, I want to know what the numbers mean. Are they array positions, exact counts, approximate measurements, or digits that must remain text? Those questions determine whether ordinary number arithmetic is enough, whether bigint helps, and whether converting the input would break the problem's rules before we've started.

This guide collects the numeric decisions that recur across algorithm problems. My individual walkthroughs explain their algorithms; here, the useful work is deciding what can safely carry the values between steps.


Three Ranges to Check

A problem's maximum input is only the first limit. Check the largest intermediate value and the required output as well.

Suppose each input is at most one million. Adding two is comfortably safe. Multiplying several together may not be. Conversely, a hundreds‑of‑digits result can be represented by an array whose individual cells hold small integers.

JavaScript's number uses binary floating‑point representation. Every integer from -(2 ** 53 - 1) through 2 ** 53 - 1 is exactly representable. Beyond that safe‑integer interval, some integers remain representable, but consecutive integers no longer reliably have distinct values. This is a precision limit, not the largest magnitude the type can hold. Number.MAX_SAFE_INTEGER explains that distinction.

For example, 2 ** 53 is representable, whilst adding one to it produces the same stored value. Number.isInteger() accepts that value; it doesn't promise that an earlier conversion or calculation preserved the intended integer.

My article on numeric validation covers the coercion checks. For exact arithmetic, I additionally need Number.isSafeInteger() and a reason the operations stay safe. A TypeScript number annotation doesn't impose an integer range.


Put the Guard Before the Arithmetic

For sums of non‑negative safe integers, the remaining capacity gives a simple precondition:

const addSafeCounts = (left: number, right: number): number => {
  if (
    !Number.isSafeInteger(left) || left < 0 ||
    !Number.isSafeInteger(right) || right < 0
  ) {
    throw new RangeError('Counts must be non-negative safe integers');
  }

  if (left > Number.MAX_SAFE_INTEGER - right) {
    throw new RangeError('Count exceeds the safe-integer range');
  }

  return left + right;
};

This deliberately handles counts, not arbitrary signed arithmetic. Since right is between zero and the maximum, the subtraction is exact and tells us whether the sum fits before constructing it. Rejecting the oversized sum is a policy choice; switching the whole calculation to bigint is another.

The same reasoning appears at a different limit in my Reverse Integer walkthrough. That challenge requires a signed 32‑bit result. JavaScript can exactly store values outside that interval, but the problem still forbids them. A language's capacity doesn't override a judge's rules.

Be especially suspicious of "the answer fits a 32‑bit integer". That may describe only the requested result. In my Coin Change II and Combination Sum IV solutions, even denominations cannot reach an odd target. The final count is zero, whilst some earlier even subtotals can have enormous counts. Those tables use bigint; the final guarantee alone doesn't justify every cell being a number.


Bitwise Operators Change the Representation

Ordinary arithmetic doesn't turn every JavaScript number into a signed 32‑bit integer. Number‑based bitwise operations do introduce 32‑bit conversions. Most produce signed results; unsigned right shift, >>>, produces an unsigned result. These examples show the consequences:

const large: number = 2 ** 32;
console.log(large | 0);        // 0
console.log((2 ** 31) | 0);    // -2147483648
console.log(-1 >>> 0);         // 4294967295
console.log(1 << 32);          // 1

The last result follows because number shift counts are reduced modulo 32. >>> also discards bits beyond 32; it isn't a general‑purpose fix for large positive integers.

That makes value | 0 a poor substitute for truncation unless the 32‑bit conversion is explicitly wanted. My Single Number solution uses XOR because its input range makes that conversion safe. Moving the same expression into an unrelated wider‑integer problem changes its meaning.

BigInt bitwise operators operate on BigInts without the ordinary number's 32‑bit truncation. Both operands must be BigInts, and there is no BigInt >>>. Choosing bigint therefore requires checking the operators too, rather than sprinkling n suffixes around until the compiler stops complaining.


Division, Remainder, and the Small Matter of minus Zero

For integer digit removal, Math.trunc() discards the fractional part towards zero. Math.floor() rounds towards negative infinity. They agree for positive values and disagree precisely when a positive‑only test suite is feeling pleased with itself.

console.log(Math.trunc(-17 / 10));  // -1
console.log(Math.floor(-17 / 10));  // -2
console.log(-17 % 10);             // -7
console.log(Object.is(Math.trunc(-0.4), -0));  // true

JavaScript's remainder follows the dividend's sign; it isn't an always‑positive modulo operation. Truncation can also produce negative zero. Usually -0 === 0 is sufficient for algorithm termination, but Object.is(-0, 0) is false and their reciprocals have different signs. Normalise zero on output if the surrounding format requires that, rather than assuming every equality test treats it identically.

For a non‑negative halving loop, Math.floor(remaining / 2) is clear. My Pow(x, n) walkthrough uses it because negating the minimum signed 32‑bit exponent produces 2 ** 31: exact as a number, troublesome as a signed bitwise operand.


Choose BigInt Before Losing the Digits

If exact integer arithmetic needs more range, convert the original integer text directly:

const original: string = '9007199254740993';
const exact: bigint = BigInt(original);
const roundedFirst: bigint = BigInt(Number(original));

console.log(exact.toString());         // 9007199254740993
console.log(roundedFirst.toString());  // 9007199254740992

const toSafeNumber = (value: bigint): number => {
  if (
    value < BigInt(Number.MIN_SAFE_INTEGER) ||
    value > BigInt(Number.MAX_SAFE_INTEGER)
  ) {
    throw new RangeError('Integer cannot be safely returned as a number');
  }
  return Number(value);
};

BigInt can't recover information already rounded away by Number(), a numeric literal, or ordinary JSON parsing. Preserve large integer inputs as strings when designing that interface. The checked conversion back is useful when a caller requires a number; a result outside the range needs a different return format.

BigInt is integer arithmetic: 7n / 2n is 3n, not 3.5. Arithmetic generally cannot mix number and BigInt operands, Math functions expect numbers, and JSON.stringify() rejects BigInts by default. For a known payload, serialising an exact count as a decimal string is straightforward, provided the reader agrees on its meaning. The BigInt reference documents these restrictions.

The snippets need a BigInt‑capable runtime and an ES2020‑or‑later TypeScript target. Compilation settings cannot supply missing runtime support.

There is also a cost to exactness. Bigger integers occupy more bits, and arithmetic cost depends on their size. Counting table cells is useful complexity analysis; treating every unbounded BigInt addition as constant work is a separate assumption.

Sometimes whole‑value conversion is forbidden anyway. My Multiply Strings solution keeps decimal columns in an array and proves the numeric buckets remain small. BigInt is useful as an independent test oracle there, but would violate the submitted solution's restrictions.


Comparisons Need the Right Question

For ordinary finite numbers, (a, b) => a - b is a familiar numeric sort comparator. A rounded difference doesn't automatically break sorting: the comparator needs its sign, not an exact distance. However, subtracting BigInts returns a BigInt, which sort() cannot use as its numeric comparator result. Compare directly:

const compareIntegers = (left: bigint, right: bigint): number =>
  left < right ? -1 : left > right ? 1 : 0;

const ordered = [9007199254740993n, -2n, 9007199254740992n]
  .sort(compareIntegers);

Sorting already‑rounded numbers cannot restore their original order. Likewise, a general number comparator needs an explicit policy if NaN is allowed; relational checks involving it don't establish an ordinary ordering.

Fractional calculations ask a different question: how close must the result be? Binary floating point can't represent every decimal fraction exactly, and Number.EPSILON describes spacing around one, not a universal tolerance. Use the problem's absolute or relative error rule. Near zero, an absolute allowance matters; for large magnitudes, relative error may be more meaningful. Don't quietly add a tolerance to exact integer counting or sort comparators.


Test the Chosen Representation

I keep cases at both signed 32‑bit limits, around Number.MAX_SAFE_INTEGER, and on either side of zero. For conversions, compare with the original decimal string, not another expression that may already have rounded. For counting algorithms, test intermediate growth as well as the final answer. Approximate arithmetic deserves its own stated error criterion.

My default remains number when the constraints justify it. I choose BigInt when exact integers need it, and digit representations when the task demands them. The useful habit is writing down that justification before the arithmetic gets a chance to disagree.


Have a complex web platform issue?

Tell me what is blocked, what has changed, and what needs to be true after the fix. I'll come back with a practical next step.