Excel Sheet Column Title
Spreadsheet programs like Excel name columns A, B, …, Z, then continue with AA, AB, …, then AAA, and so forth. Given a positive integer columnNumber — where 1 corresponds to A, 2 to B, …, 26 to Z, and 27 to AA — return the matching column title as a string.
Think of it as base-26, except the digits start counting from 1 instead of 0, unlike ordinary binary or decimal place-value systems.
Input Format
Implement convertToTitle(columnNumber). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 · Run Sample
Input
columnNumber = 1 Output
"A" Example 2
Input
columnNumber = 28 Output
"AB" Example 3
Input
columnNumber = 701 Output
"ZY" Constraints
- 1 <= columnNumber <= 2^31 - 1
Test Cases (3)
Case 1
Args: [1]
Expected: "A"
Case 2
Args: [28]
Expected: "AB"
Case 3
Args: [701]
Expected: "ZY"
Base-26 Conversion
function convertToTitle(columnNumber) {
let result = '';
while (columnNumber > 0) {
columnNumber--;
result = String.fromCharCode(65 + (columnNumber % 26)) + result;
columnNumber = Math.floor(columnNumber / 26);
}
return result;
}Time: O(log n) | Space: O(log n), including the output string
Saved in this browser only. Private to you.