Excel Sheet Column Title Explained
Problem Statement
Given a positive integer n
, convert it to its corresponding Excel sheet column title. Excel columns are labeled as A (1), B (2), ..., Z (26), AA (27), AB (28), and so on, resembling a base-26 number system where digits are letters A-Z. This problem tests your ability to handle number-to-string conversion with custom base systems.
Example
Input: n = 28
Output: "AB"
Explanation: 28 corresponds to AA (27) + B (2) = AB.
Code
Java
Python
JavaScript
public class Solution { public String convertToTitle(int n) { StringBuilder sb = new StringBuilder(); while (n > 0) { n--; sb.append((char) ('A' + (n % 26))); n /= 26; } return sb.reverse().toString(); } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.convertToTitle(28)); // "AB" } }
def convert_to_title(n): result = [] while n > 0: n -= 1 result.append(chr(ord('A') + (n % 26))) n //= 26 return ''.join(result[::-1]) # Example usage print(convert_to_title(28)) # "AB"
function convertToTitle(n) { let result = ''; while (n > 0) { n--; result = String.fromCharCode('A'.charCodeAt(0) + (n % 26)) + result; n = Math.floor(n / 26); } return result; } // Example usage console.log(convertToTitle(28)); // "AB"
Explanation
- Excel columns use a base-26 system, but 1-based (A=1, not 0).
- Subtract 1 from
n
to adjust to 0-based for modulo and division. - Extract the remainder modulo 26 to get the current letter (0=A, 1=B, ..., 25=Z).
- Divide
n
by 26 to process the next digit. - Reverse the result since digits are computed from least to most significant.
Note
The time complexity is O(log n) with base 26. Be cautious with the 1-based indexing adjustment to avoid off-by-one errors.