Excel Sheet Column Title

Turn a column number into the letters a spreadsheet shows above that column, such as 28 into AB.

A spreadsheet names its columns with letters: the first 26 are A to Z, and the next ones are AA, AB, and so on. Given a column number columnNumber, counting from 1, return the title of that column. For example, 1 is "A", 26 is "Z", 27 is "AA" and 28 is "AB".

Example 1
Input: columnNumber = 1
Output: "A"
Example 2
Input: columnNumber = 28
Output: "AB"
Example 3
Input: columnNumber = 701
Output: "ZY"
Solution

The Idea

Scroll right in a spreadsheet and watch the letters above the columns. They run A, B, ... Z, and after Z comes AA, then AB, all the way to AZ. Then BA starts. It looks like a car's mileage counter rolling over, but with letters instead of digits.

There is one difference from a mileage counter. Its digits run 0 to 9, so 9 rolls over to 10, a two-digit number that starts with 1 and ends in 0. The letters here are worth 1 to 26, A being 1 and Z being 26, and there is no letter for 0. So after Z comes AA, at the point where a mileage counter would show 10.

Seen that way, a title is a number written with letters as digits, where each place to the left is worth 26 times more. The title "AB" has A in the 26s place and B in the ones place: 1 × 26 + 2 = 28, which is Example 2. The title "ZY" is 26 × 26 + 25 = 676 + 25 = 701, which is Example 3.

Going the other way is the real question. For a decimal number, the last digit is the remainder after dividing by 10. Can the last letter come from the remainder after dividing by 26? For 28 it works: the remainder is 2, the letter B. For 26 it fails: the remainder is 0, and no letter stands for 0, yet the answer should be Z.

The fix is to subtract 1 before dividing. That moves the last letter's value from 1 to 26 down to 0 to 25, so A is 0, B is 1 and Z is 25, and every remainder now names a letter. The picture below follows 701 through this.

Converting 701. Pass 1: 701 minus 1 is 700; 700 divided by 26 leaves remainder 24, the letter A + 24 = Y, and quotient 26. Pass 2: 26 minus 1 is 25; remainder 25 is Z and quotient 0 stops. The letters Y, Z reversed give the title ZY.

In the row labelled pass 1, 701 becomes 700. Dividing 700 by 26 gives 26, with 24 left over, and A + 24 is Y, the last letter. The quotient, 26, is the number left for the letters before Y, so the dashed arrow carries it down to pass 2.

In pass 2, 26 becomes 25, the remainder is 25, and A + 25 is Z. The quotient is 0, so no letters remain. The letters came out last first, Y and then Z, and reading them backwards gives the title "ZY", as the box at the bottom shows.

Solution Approach

The method has four things to get right: how to read the last letter, what number is left for the letters before it, how to put the letters in order, and whether a large input can overflow.

Reading the last letter

Why not treat the title as an ordinary base-26 number, with A as 0 and no subtraction? Run that version and it returns "B" for 1, "BA" for 26 and "BC" for 28. Every column is off, because A now stands for 0 while columns start at 1.

Subtracting 1 first fixes this. Say the title's last letter is worth some value from 1 to 26, and the letters before it form a number called rest. Then the column number is rest × 26 + value, and one less is rest × 26 + (value - 1). Since value - 1 lies between 0 and 25, it is exactly the remainder after dividing by 26.

The number left for the letters before

What does the division leave for the rest of the title? From that same formula, the quotient of (columnNumber - 1) / 26 is rest. That is a column number in its own right, the one the earlier letters spell, so the same step repeats on it. Each pass subtracts 1 again, because every place has the same 1-to-26 letters.

The repeating stops when the quotient reaches 0, as in pass 2 for 701. Look at 52: one less is 51, and 51 divided by 26 gives remainder 25, a Z, and quotient 1. Then 1 minus 1 is 0, and 0 divided by 26 gives remainder 0, an A, and quotient 0. Read backwards, that is "AZ".

Putting the letters in order

The letters come out from right to left. Collecting them in a StringBuilder, Java's growable string, and reversing it once at the end puts them in reading order. Adding each letter at the front instead also works, but every insert shifts the letters already there.

Large inputs and overflow

Could the arithmetic go past what an int can hold? The loop only subtracts 1 from a positive number and divides by 26, so the value never grows past the input. Even the largest int, Integer.MAX_VALUE, needs no long, and the run below converts it.

Java Solution

The method convertToTitle works in these steps:

  1. First, create an empty StringBuilder named sb to collect the letters.
  2. Loop while columnNumber is greater than 0. Inside, subtract 1 from columnNumber, so the last letter's value lies between 0 and 25.
  3. Append the letter 'A' + columnNumber % 26 to sb, cast back to a char.
  4. Divide columnNumber by 26, which leaves the number for the letters before this one, and go round the loop again.
  5. When the loop ends, reverse sb and return it as a string.

The main method runs the three examples, then 26, 27, 52, 702 and 703 where the letters roll over, then 0 and Integer.MAX_VALUE.

Java
public class ExcelSheetColumnTitle {

    public static String convertToTitle(int columnNumber) {
        StringBuilder sb = new StringBuilder();
        while (columnNumber > 0) {
            columnNumber--;                   // letters are worth 1..26, shift to 0..25
            sb.append((char) ('A' + columnNumber % 26));
            columnNumber /= 26;               // what is left for the letters before it
        }
        return sb.reverse().toString();       // the last letter was found first
    }

    public static void main(String[] args) {
        int[] tests = {1, 28, 701, 26, 27, 52, 702, 703, 0, Integer.MAX_VALUE};
        for (int n : tests) {
            System.out.println(n + " -> \"" + convertToTitle(n) + "\"");
        }
    }
}

Running it prints:

Output
1 -> "A"
28 -> "AB"
701 -> "ZY"
26 -> "Z"
27 -> "AA"
52 -> "AZ"
702 -> "ZZ"
703 -> "AAA"
0 -> ""
2147483647 -> "FXSHRXW"

Look at 26 -> "Z" and 27 -> "AA": the title rolls over from one letter to two exactly when the numbers pass 26. The same happens at three letters, where 702 is "ZZ" and 703 is "AAA". The line for 52 matches the "AZ" worked out by hand.

The line 0 -> "" shows that 0, which names no column, skips the loop and gives an empty title. The last line converts 2,147,483,647, the largest int, to the seven letters "FXSHRXW" with no overflow.

Complexity

Each pass of the loop produces one letter of the title, and one reverse puts the letters in order.

  • Time: O(log26 n) for column number n, because each pass adds one letter and divides columnNumber by 26, so a title of seven letters, the longest an int gives, takes seven passes.
  • Space: O(log26 n) for the title, because sb and the returned string each hold one character per letter of the title.

The reverse conversion, from a title back to its number, is Excel Sheet Column Number.