Excel Sheet Column Number

Easy · Math & Geometry · Explanation and code example

Base-26 Accumulation

How it works

Excel columns use digits A through Z with values one through 26. Read left to right: multiplying the previous total by 26 shifts it one place, and adding the new letter’s value extends the column number. There is no zero digit.

Steps

  1. Initialize the total to zero.
  2. For each letter, multiply the total by 26.
  3. Add its one-based letter value.

Complexity

  • Time: O(n) for n letters.
  • Space: O(1).

Things to watch for

  • A maps to one, rather than zero.
  • For AB, the result is 1 × 26 + 2 = 28.
  • Do not treat the title as ordinary zero-based base 26.

Python code example

import functools

class Solution:
  def titleToNumber(self, columnTitle: str) -> int:
    return functools.reduce(lambda subtotal, c:
                            subtotal * 26 + ord(c) - ord('@'), columnTitle, 0)

C++ code example

class Solution {
 public:
  int titleToNumber(string columnTitle) {
    return accumulate(columnTitle.begin(), columnTitle.end(), 0,
                      [](int acc, char c) { return acc * 26 + (c - 'A' + 1); });
  }
};
Source and license

Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations