Excel Sheet Column Title

XXX. Excel Sheet Column Title

Math
String

Problem Statement:

Given a positive integer n, return its corresponding column title as it would appear in an Excel sheet. For example:

  • 1 → "A"
  • 28 → "AB"
  • 701 → "ZY"

Algorithm:

  1. Initialize an empty StringBuilder to construct the result.
  2. While n is not 0:
    • Find the corresponding character for the current digit using (n - 1) % 26.
    • Subtract 1 from n and divide by 26 to shift to the next position.
    • Insert the character at the beginning of the string to build the title in reverse.
  3. Return the constructed string.

Complexity:

Time Complexity: O(log26(n)), since we divide n by 26 in each iteration.
Space Complexity: O(log26(n)), for the StringBuilder.

Java Implementation:


public String convertToTitle(int n) {
    StringBuilder sb = new StringBuilder();
    // Loop until n becomes 0
    while (n != 0) {
        // Calculate the character for the current position
        char next = (char) ((n - 1) % 26 + 'A');
        sb.insert(0, next); // Insert the character at the beginning
        n = (n - 1) / 26;   // Move to the next position
    }
    return sb.toString(); // Return the constructed title
}
                

Python Implementation:


def convertToTitle(n):
    result = []
    while n > 0:
        n -= 1  # Adjust for 0-indexing
        result.append(chr(n % 26 + ord('A')))
        n //= 26  # Move to the next position
    return ''.join(reversed(result))
                

C++ Implementation:


string convertToTitle(int n) {
    string result = "";
    while (n > 0) {
        n--; // Adjust for 0-indexing
        result = char(n % 26 + 'A') + result;
        n /= 26; // Move to the next position
    }
    return result;
}
                
Previous
Previous

First Bad Version

Next
Next

Symmetric Tree