Implement numbering scheme like A,B,C… AA,AB,… AAA…, similar to converting a number to radix26(实现像 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
这篇关于实现像 A,B,C... AA,AB,... AAA... 这样的编号方案,类似于将数字转换为 radix26的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实现像 A,B,C... AA,AB,... AAA... 这样的编号方案,类似于将数字转换为 radix26


- Flexslider 箭头未正确显示 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01