# Accepted simple java solution and how to improve?

• ``````public class Solution {
public String convertToTitle(int n) {
StringBuilder result = new StringBuilder();
while(n > 0) {
if(n % 26 == 0) {
result.append('Z');
} else {
result.append((char) ('A' + n%26 - 1));
}
n = (n - 1) / 26;
}
return result.reverse().toString();
}
}``````

• ``````char *convertToTitle(int n) {
int len=0;
char *result;
int temp=n;
while(temp)
{
temp=(temp-1)/26;
len++;
};
result=(char *)malloc((len+1)*sizeof(char));
result[len]='\0';
while(n)
{
result[--len]=(n-1)%26+'A';
n=(n-1)/26;
};
return result;
}```````

• thank you! i also have this solution,do you have another solution with java ?

• ``````public class Solution
{
public String convertToTitle(int n)
{
final StringBuilder sb = new StringBuilder();
for (; n > 0; n /= 26)
{
sb.insert(0, (char)(--n % 26 + 'A'));
}

return sb.toString();
}
}``````

• public class Solution {

``````public String convertToTitle(int n) {
StringBuilder builder = new StringBuilder();
while (n > 0) {
char c = (char) ('A' + (n - 1) % 26);
builder.append(c);
n = (n - 1) / 26;
}
return builder.reverse().toString();
}
``````

}

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

Hope to help.

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