问题描述
可能重复:
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 .....
有关的,继承人的code:
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 ?
推荐答案
这个系统类似于 Hexavigesimal 一>(与A = 0开始),被称为双射基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;
}
从本质上讲,你从hexavigesimal转换为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
Which gives you 28.
另外一个例子:
2 1 0 (positions)
A B C
+ + +
| | |
| | +----> 3 * (26 ^ 0) +
| +------> 2 * (26 ^ 1) +
+--------> 1 * (26 ^ 2)
= 731
这篇关于实现如A,B,C ... AA编号方案,AB,... AAA ...,类似于将数字转换radix26的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!