Excel Sheet Column Title

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. For example: 1 → "A", 2 → "B", ..., 26 → "Z", 27 → "AA", 28 → "AB", ..., 701 → "ZY".

Example 1
Input: columnNumber = 1
Output: "A"
Example 2
Input: columnNumber = 28
Output: "AB"
Explanation: 28 = 1*26 + 2, so the title is "AB".
Example 3
Input: columnNumber = 701
Output: "ZY"

Solution Approach

This is a decimal-to-base-26 conversion, but the alphabet is 1-indexed (A=1 through Z=26) with no zero digit. The key trick is to decrement columnNumber by 1 before each modulo operation to shift to 0-indexed temporarily.

  • While columnNumber > 0: decrement by 1, then get remainder (columnNumber - 1) % 26.
  • Prepend the character 'A' + remainder to the result.
  • Divide: columnNumber = (columnNumber - 1) / 26.
  • Reverse the accumulated string and return.
Java
class Solution {
    public String convertToTitle(int columnNumber) {
        StringBuilder sb = new StringBuilder();
        while (columnNumber > 0) {
            columnNumber--;
            sb.append((char) ('A' + columnNumber % 26));
            columnNumber /= 26;
        }
        return sb.reverse().toString();
    }
}
Complexity Analysis:

Time complexity: O(log₂₆ n). Number of characters in the result.
Space complexity: O(log₂₆ n). Space for the result string.