You are given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...Example 1:
Input: columnNumber = 32
Output: "AF"Example 2:
Input: columnNumber = 53
Output: "BA"Constraints:
1 <= columnNumber <= ((2^31)-1)Excel columns use a bijective base-26 system where A=1, B=2, ..., Z=26. Unlike standard base conversion where digits range from 0 to base-1, here digits range from 1 to 26. This means we need to adjust by subtracting 1 before finding each digit.
After subtracting 1, we can use modulo 26 to find the rightmost character and divide by 26 to get the remaining prefix. Recursion handles this naturally: first solve for the prefix (if any), then append the current character.
columnNumber is 0, return an empty string.1 from columnNumber to convert to 0-indexed.n // 26 to get the prefix string.chr('A' + n % 26).Where is the given column number.
The iterative approach works from right to left, building the result string in reverse. At each step, we extract the rightmost character, then reduce the number for the next iteration. Since we build characters from least significant to most significant, we reverse the result at the end.
This avoids recursion overhead and makes the process explicit: subtract 1, find the character via modulo, divide by 26, and repeat until the number becomes 0.
res to collect characters.columnNumber > 0:columnNumber by 1.columnNumber % 26.chr('A' + offset) to res.columnNumber by 26.res and join to form the final string.Where is the given column number.
Unlike standard base conversion where digits range from 0 to 25, Excel columns use a 1-indexed system where A=1 and Z=26. Forgetting to subtract 1 before taking modulo will cause off-by-one errors. For example, column 26 should be "Z", but without the subtraction, you would incorrectly compute the character for position 0.
When building the string iteratively by repeatedly taking modulo and dividing, you generate characters from least significant (rightmost) to most significant (leftmost). If you forget to reverse the accumulated characters at the end, "ABC" would incorrectly become "CBA". Either build the string in reverse or explicitly reverse it before returning.