3

Possible Duplicate:
Xnary (like binary but different) counting

In JavaScript, I want to implement a numbering scheme in JavaScript so that 1 is A, 2 is B, .... 26 is Z, 27 is AA, 28 is AB .....

For that, heres the code:

function convertor(n){

     var x = n-1,
         baseCharCode = "A".charCodeAt(0);

     var arr = x.toString(26).split(''),
         len = arr.length;

     return arr.map(function(val,i){
         val = parseInt(val,26);

         if( (i === 0) && ( len > 1)){
              val = val-1;
         }

         return String.fromCharCode(baseCharCode + val);
     }).join('');
}

It seems to work fine, but any ideas to optimize it or another way of implementing it ?

Community
  • 1
  • 1
sbr
  • 4,735
  • 5
  • 43
  • 49

1 Answers1

4

This system is similar to Hexavigesimal (which starts with A = 0) and is called bijective base-26 (it has no 0). You can convert it using standard base-conversion arithmetic like this:

function toDecimal(str) {
    var decimal = 0;
    var letters = str.split(new RegExp());

    for(var i = letters.length - 1; i >= 0; i--) {
        decimal += (letters[i].charCodeAt(0) - 64) * (Math.pow(26, letters.length - (i + 1)));
    }

    return decimal;
}

Essentially, you convert from hexavigesimal to base 10 as follows. Assume you have to string "AB". What you have then is:

1 0 (positions)
---
A B
+ +
| |
| +----> 2 * (26 ^ 0) +
+------> 1 * (26 ^ 1)
       = 28

Which gives you 28.

Another example:

2 1 0 (positions)
A B C
+ + +
| | |
| | +----> 3 * (26 ^ 0) +
| +------> 2 * (26 ^ 1) +
+--------> 1 * (26 ^ 2)
           = 731
Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295