public class Solution {
public String convertToTitle(int n) {
StringBuilder result = new StringBuilder();
while(n>0){
n;
result.insert(0, (char)('A' + n % 26));
n /= 26;
}
return result.toString();
}
}
Accepted Java solution

using simple string basically copies to a new variable, then add the new character to it. so, every time you add a character into a string, it copies the entire string, then adds the new character. StringBuilder doesn't copy that string into a new variable, so it is more memoryefficient

Inserting to the beginning of StringBuilder actually takes O(n). see http://stackoverflow.com/questions/5931261/javausestringbuildertoinsertatthebeginning


said in Accepted Java solution:
(char)('A' + n % 26))
can some one explaun the line result.insert(0, (char)('A' + n % 26));

@vishrutsharma7 Think of it as normalizing the integer result to A through Z.
e.g. if n is 25, n%26 = 25, so 'A' + 25 = 'Z'
e.g. if n is 26, n%26 = 0, so 'A' + 0 = 'A'.
e.g. if n is 27, n%26 = 1, so 'A' + 1 = 'B'Hope that clarifies it. Note, he does n before that line, so it appropriate maps the n value to the correct integer.

Insert a char at the beginning is not very efficient. The complexity will be n^2. We can append the character to the end and reverse the string in the end, and the complexity will be linear.
public class Solution { public String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while (n > 0) { n; result.append((char)('A' + n % 26)); n /= 26; } result.reverse(); return result.toString(); } }



@fsr0023120 Actually your way is more efficient. insert to 0 offset will cause the shifting of the current chars (just like insert to 0 offset of an array)
