LeetCode – Excel Sheet Column Title (Java)

Problem

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

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 

Java Solution

This problem is the reverse version of Excel Sheet Column Number.

The key is n--. The minimum in 26-bit number is mapped to 1, not 0.

public String convertToTitle(int n) {
    if(n <= 0){
        throw new IllegalArgumentException("Input is not valid!");
    }
 
    StringBuilder sb = new StringBuilder();
 
    while(n > 0){
        n--;
        char ch = (char) (n % 26 + 'A');
        n /= 26;
        sb.append(ch);
    }
 
    sb.reverse();
    return sb.toString();
}

7 thoughts on “LeetCode – Excel Sheet Column Title (Java)”

  1. static String ColToString(int col) {
    int rem=col%26;
    if(rem==0) {
    col–;
    rem=26;
    }
    String s=””;
    if(col>26){
    col/=26;
    s=ColToString(col)+String.valueOf((char)(rem+64));
    }
    else {
    s+=String.valueOf((char)(rem+64));
    }
    return s;

    }

  2. There is no need to use a StringBuilder.

    string s = "";
    while(n>0)
    {
    n--;
    s = ((char)(n%26 +'A')).ToString() + s;
    n/=26;
    }
    return s;

    Leetcode accepted this.
    Thank you for the simple solution!

Leave a Comment