Excel Column ↔ NumberLoading saved progress…

Excel Column ↔ Number

A spreadsheet labels its columns with letters instead of digits: A is column 1, Z is 26, then it rolls over to AA for 27, AZ for 52, BA for 53, all the way to ZZ (702) and AAA (703). It looks like counting in base-26 with letters for digits, but there is a catch — there is no zero. The letters run A=1 to Z=26 with nothing standing for zero, which makes this a bijective base-26 system (see bijective numeration). You will convert both directions, packaged on one object as excelColumnNumber = { toNumber, toTitle }.

Signature

excelColumnNumber.toNumber(title)  // column title string -> integer (1-based)
excelColumnNumber.toTitle(n)       // integer (n >= 1) -> column title string

toTitle is the exact inverse of toNumber: toNumber(toTitle(n)) returns n.

Examples

excelColumnNumber.toNumber('A');    // 1
excelColumnNumber.toNumber('Z');    // 26
excelColumnNumber.toNumber('AA');   // 27
excelColumnNumber.toNumber('ZZ');   // 702
excelColumnNumber.toTitle(1);    // 'A'
excelColumnNumber.toTitle(26);   // 'Z'
excelColumnNumber.toTitle(27);   // 'AA'
excelColumnNumber.toTitle(703);  // 'AAA'

Notes

  • No zero digit — the letters run A=1 to Z=26, and 26 is a single letter Z, not a carry into two letters. This is what makes the system bijective base-26 rather than ordinary base-26.
  • Uppercase only — titles are uppercase AZ. toNumber may assume its input is a valid, non-empty uppercase title; you do not need to reject bad input.
  • toTitle domainn is always 1 or greater. There is no column 0 and no negative column.
  • Round-triptoNumber(toTitle(n)) must equal n for every n >= 1. Build both functions yourself; no libraries.

FAQ

Why subtract 1 from n before each digit in toTitle?
Because spreadsheet columns are bijective base-26 — there is no zero digit. Without the subtraction, every exact multiple of 26 leaves a remainder of 0, which has no letter. Subtracting 1 first shifts the value into the range 0 to 25 so that 26 maps to Z and stops, instead of carrying a bogus zero digit.
How is this different from ordinary base-26?
Ordinary base-26 has digits 0 through 25, so 26 is written as the two-digit 10. Excel columns have no zero: the letters run A=1 to Z=26, and 26 stays a single letter Z. Only 27 carries into a second letter as AA. That missing zero is the entire difference and the reason toTitle needs the minus-one shift.
What is the time complexity?
Both directions are linear in the number of letters, which is O(log n) in the column number — toNumber does one multiply-add per character, and toTitle does one divide per letter it emits.
Loading editor…