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".
Output: "A"
Output: "AB"
Explanation: 28 = 1*26 + 2, so the title is "AB".
Output: "ZY"
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' + remainderto the result. - Divide:
columnNumber = (columnNumber - 1) / 26. - Reverse the accumulated string and return.
Complexity Analysis:
Time complexity: O(log₂₆ n) — number of characters in the result.
Space complexity: O(log₂₆ n) — space for the result string.