实现像 A,B,C... AA,AB,... AAA... 这样的编号方案,类似于将数字转换为 radix26

可能重复:
Xnary(类似于二进制但不同)计数

在 JavaScript 中,我想在 JavaScript 中实现一个编号方案,以便 1 是 A,2 是 B,....26 是 Z,27 是 AA,28 是 AB .....

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 .....

为此,代码如下:

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 ?

推荐答案

这个系统类似于Hexavigesimal(以 A = 0 开头)并称为双射 base-26(它没有 0).您可以使用标准的基本转换算法来转换它,如下所示:

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;
}

基本上,您从十六进制转换为以 10 为底,如下所示.假设您必须字符串AB".你所拥有的是:

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

这给你 28.

另一个例子:

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

相关文章