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();
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Arjun Dubashi

    You use a string builder because string concantenation operates in O(N^2) time

  • m00dy

    Noob

  • Anna Kulik

    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!