Skip to content

How can we write an optimal function to get alphabetical sequence for a given number?

An answer to this question on Stack Overflow.

Question

I want a function like

string getAlphabetEncoding(num){
    //some logic
    return strForNum;
}

input: 1 output: a, input: 5 output: e, input: 27 output: aa, input: 676 output: YZ, input: 677 output: za...

Answer

I think you are trying to convert from Base 10 to Bijective Base 26 (spreadsheet column notation), otherwise known as the hexavigesimal system.

You list JavaScript as a language of interest, so I have targeted it. The code below performs that conversion, but note that the outputs are not what you suggest in your question. I have verified them with my spreadsheet program and found them to be correct, so I am assuming the values in our question are wrong.

Number.prototype.toBijectiveBase26 = (function () {
  return function toBijectiveBase26() {
    n = this
    ret = "";
    while(parseInt(n)>0){
      --n;
      ret += String.fromCharCode("A".charCodeAt(0)+(n%26));
      n/=26;
    }
    return ret.split("").reverse().join("");
  };
}());
Number(1).toBijectiveBase26();   //Returns A
Number(5).toBijectiveBase26();   //Returns E
Number(27).toBijectiveBase26();  //Returns AA
Number(676).toBijectiveBase26(); //Returns YZ
Number(677).toBijectiveBase26(); //Returns ZA