I have a working code (below) to convert a number
to Excel-like (A...Z AA...AZ BA...BZ ...ZA-ZZ
) column codes (headers).
For simplicity I limited it to 1 or 2 character codes.
Can the algorithm be streamlined by using a bit more of elementary math or using it differently?
Please note that I just happened to need it in JavaScript (so I wrote it in JS) and am not looking for pure code improvements.
function numberToLetters(nNum) {
var result;
if (nNum <= 26) {
result = letter(nNum);
} else {
var modulo = nNum % 26;
var quotient = Math.floor(nNum / 26);
if (modulo === 0) {
result = letter(quotient - 1) + letter(26);
} else {
result = letter(quotient) + letter(modulo);
}
}
return result;
}
function letter(nNum) {
var a = "A".charCodeAt(0);
return String.fromCharCode(a + nNum - 1);
}