可能重复: Convert a number to the shortest possible character string while retaining uniqueness
我想数点什么,我只有一个数字来报告结果,所以我想用字母表示数字> 9。
1 => 1
5 => 5
10 => A
30 => U
55 => u // I may have an off-by-one error here -- you get the idea
>61 => z // 60 will be more than enough, so I'll use z to mean "at least 62"使用javascript最简单的方法是什么?
发布于 2012-06-26 21:10:10
我认为第36垒足够好:
function oneDigit(n) {
var BASE=36;
if (n >= BASE-1) { n = BASE-1; }
return n.toString(BASE);
}发布于 2012-06-26 21:01:35
以下是许多方法中的一种:
function num2letter(num) {
if( num > 61) return "z";
if( num < 0) return num;
return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[num];
}发布于 2012-06-26 21:20:43
另一种方法是:
function parse(x)
{
if(x<10)return x;
else if(x<36)return String.fromCharCode(x+55).toUpperCase();
else if(x<62)return String.fromCharCode(x+29).toLowerCase();
else return "z";
}这个小小的考验:
var res="";
for(var a=-10;a<70;a++)res+=a+" -> "+parse(a)+"\n";
alert(res);还有小提琴:http://jsfiddle.net/nD59z/4/
以同样的方式,但以较少的字符和难以理解的:
function parse(x)
{
return x<10?x:(x<36?String.fromCharCode(x+55).toUpperCase():(x<62?String.fromCharCode(x+29).toLowerCase():"z"));
}https://stackoverflow.com/questions/11215787
复制相似问题