JavaScript - 字母序列
JavaScript - Sequence of letters
我想创建一个函数,它应该 return 来自序列
的第 n 个字符串
a, b, c, ... , z, aa, ab, ... , az, ba, ... , zz, aaa, ...
对于给定的数字 n(索引从零开始)。
这是我当前的函数:
const charCode = 'a'.charCodeAt(0);
function identName(a){
var b = '';
while(a){
b = String.fromCharCode(charCode + a % 26) + b;
a = a / 26 | 0;
}
return b || 'a';
}
有 26 个字母,所以我除以 26,每次我将余数(模 26)的字符代码连接到字符串 b
。然而这是输出:
a b c d e f g h i j k l m n o p q r s t u v w x y z ba bb bc bd be ...
可以看到,两个字母串是从ba
开始的。我试图在每次迭代中减少 1,但结果是这样的:
a a b c d e f g h i j k l m n o p q r s t u v w x y a' aa ab ac ad ...
有两次字符串a
,没有z
。我究竟做错了什么?如何以最佳和快速的方式正确生成这个序列?
编辑
我真的看不出我的问题有什么不清楚的地方。我只是想要一个像这样调用的函数 identName(0)
和 returns "a"
,当像这样调用时 identName(1)
returns "b"
,等等...,当这样调用时:identName(26)
returns "aa"
等等。怎么形容更简单。我真的不明白这里有什么不清楚...:/
这应该可以解决问题。
const charCode = 'a'.charCodeAt(0);
var identName = function (a) {
var b = [a], sp, out, i, div;
sp = 0;
while(sp < b.length) {
if (b[sp] > 25) {
div = Math.floor(b[sp] / 26);
b[sp + 1] = div - 1;
b[sp] %= 26;
}
sp += 1;
}
out = "";
for (i = 0; i < b.length; i += 1) {
out = String.fromCharCode(charCode + b[i]) + out;
}
return out;
}
本质上,每次进入转换时,您都会跳过 0 个位置,例如 27 -> 0,0 而不是 1,0。
我想创建一个函数,它应该 return 来自序列
的第 n 个字符串a, b, c, ... , z, aa, ab, ... , az, ba, ... , zz, aaa, ...
对于给定的数字 n(索引从零开始)。
这是我当前的函数:
const charCode = 'a'.charCodeAt(0);
function identName(a){
var b = '';
while(a){
b = String.fromCharCode(charCode + a % 26) + b;
a = a / 26 | 0;
}
return b || 'a';
}
有 26 个字母,所以我除以 26,每次我将余数(模 26)的字符代码连接到字符串 b
。然而这是输出:
a b c d e f g h i j k l m n o p q r s t u v w x y z ba bb bc bd be ...
可以看到,两个字母串是从ba
开始的。我试图在每次迭代中减少 1,但结果是这样的:
a a b c d e f g h i j k l m n o p q r s t u v w x y a' aa ab ac ad ...
有两次字符串a
,没有z
。我究竟做错了什么?如何以最佳和快速的方式正确生成这个序列?
编辑
我真的看不出我的问题有什么不清楚的地方。我只是想要一个像这样调用的函数 identName(0)
和 returns "a"
,当像这样调用时 identName(1)
returns "b"
,等等...,当这样调用时:identName(26)
returns "aa"
等等。怎么形容更简单。我真的不明白这里有什么不清楚...:/
这应该可以解决问题。
const charCode = 'a'.charCodeAt(0);
var identName = function (a) {
var b = [a], sp, out, i, div;
sp = 0;
while(sp < b.length) {
if (b[sp] > 25) {
div = Math.floor(b[sp] / 26);
b[sp + 1] = div - 1;
b[sp] %= 26;
}
sp += 1;
}
out = "";
for (i = 0; i < b.length; i += 1) {
out = String.fromCharCode(charCode + b[i]) + out;
}
return out;
}
本质上,每次进入转换时,您都会跳过 0 个位置,例如 27 -> 0,0 而不是 1,0。