这个函数根据一个数字返回3个字符:
function n2s (n) {
var s = '';
while (s.length < 3) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
打印从“aaa”到“zzz”的字符串:
var zzz = Math.pow(26, 3) - 1;
for (var n = 0; n <= zzz; n++) {
console.log(n2s(n));
}
function n2s (n) {
var s = '';
while (s.length < 3) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
var result = [];
var zzz = Math.pow(26, 3) - 1;
for (var n = 0; n <= zzz; n++) {
result.push(n2s(n));
}
document.body.innerHTML = result.join(' ');
请求细节:-)
改进
与接受的答案相比,性能提升:http://jsperf.com/10-to-26。
function s2n(s) {
var pow, n = 0, i = 0;
while (i++ < s.length) {
pow = Math.pow(26, s.length - i);
n += (s.charCodeAt(i - 1) - 97) * pow;
}
return n;
}
function n2s(n) {
var s = '';
if (!n) s = 'a';
else while (n) {
s = String.fromCharCode(97 + n % 26) + s;
n = Math.floor(n / 26);
}
return s;
}
function pad (s, n) {
while (s.length < n) s = 'a' + s;
return s;
}
使用方法:
var from = s2n('azx');
var to = s2n('baa');
for (var n = from; n <= to; n++) {
console.log(pad(n2s(n), 3));
}
输出:
azx
azy
azz
baa
递归
可能会在内存使用或计算时间方面效率较低:https://jsperf.com/10-to-26/4。
function n2s(n) {
var next = Math.floor(n / 26);
return (
next ? n2s(next) : ''
) + (
String.fromCharCode(97 + n % 26)
);
}
function s2n(s) {
return s.length && (
(s.charCodeAt(0) - 97)
) * (
Math.pow(26, s.length - 1)
) + (
s2n(s.slice(1))
);
}