# Accepted simple Java solution 0ms

• ``````public class Solution {
public String convertToTitle(int n) {
StringBuilder str = new StringBuilder();

while(n>0){
n--;
str.append((char)((n%26) + 'A'));
n/=26;
}
return str.reverse().toString();
}
}``````

• I really like this solution, and have added comments to it and refactored slightly:

``````public class Solution {

/**
* Given a positive integer, return its corresponding column title as it
* would appear in an Excel sheet.
*
* Ex. 1 -> A, 26 -> Z, 27 -> AA, 52 -> AZ
* @param n The positive integer to convert.
* @return The corresponding Excel-style column title.
*/
public String convertToTitle(int n) {

// Handle invalid input
if (n < 1) return "";

/**
* Use StringBuilder as a stack, to which we will append Characters,
* starting with the last character in the Title, and ending with
* the first.
*/
StringBuilder sb = new StringBuilder();
while (n > 0) {

/**
* Fix the indexing.
*
* From the problem statement, 1 -> A, and 26 -> Z,
* but there are only 26 letters, and 26 % 26 is 0.
*
* Accordingly, shift indexing 1 to the left, so that 0 -> A and
* so that we don't wrap around until we get to 26.
*/
n--;

/**
* Since chars are just numbers, increase this "place"
* by 'A' and cast to char
*/
sb.append((char) (n % 26 + 'A'));

/**
* Move to the next-higher "place" in the base-10 representation
* of our Title.
*/
n /= 26;
}

/**
* We appended the smaller places first, followed by the larger ones,
* so we need to reverse our StringBuilder before we return its String.
*/
return sb.reverse().toString();
}
}
``````

• @GrubenM Thanks!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.