将数字转换为尽可能短的字符串,同时保留唯一性 [英] Convert a number to the shortest possible character string while retaining uniqueness
问题描述
我有一个数字,比如123456,我需要将它映射到字符串,任何字符串。地图函数的唯一约束是:
I have a number, say "123456", and I need to map it to a string, any string. The only constraint on the map functions are:
- 每个数字必须映射到唯一的字符串(这意味着字符串可以任意长)
- 字符串只能包含0-9,az,AZ
什么地图功能会产生最短的字符串?
What map function would produce the shortest strings?
首选JavaScript解决方案。
Solutions in JavaScript are preferred.
注意:显然最简单的解决方案是使用原始号码,所以请确保您的解决方案比这更好。
Note: Clearly the simplest solution is to use the original number, so make sure you solution does better than that.
推荐答案
您可能需要使用 Base 36 或 Base 62 。
对于不区分大小写的字母数字字符,Base 36将是最紧凑的,但如果你想利用区分大小写,Base 62的紧凑性会大约增加20%。
Base 36 would be the most compact for case-insensitive alphanumerical characters, but if you want to exploit case-sensitivity, Base 62 would be approximately 20% more compact.
对于Base 36,您可以轻松使用JavaScript的 Number.toString(radix)
方法,如下所示:
For Base 36, you can easily use JavaScript's Number.toString(radix)
method, as follows:
var n = 123456;
n.toString(36); // returns: "2n9c"
对于Base 62,您可能需要检查此论坛帖子。基本上你应该能够做到以下几点:
For Base 62, you may want to check this forum post. Basically you should be able to do the following:
Number.prototype.toBase = function (base) {
var symbols =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var decimal = this;
var conversion = "";
if (base > symbols.length || base <= 1) {
return false;
}
while (decimal >= 1) {
conversion = symbols[(decimal - (base * Math.floor(decimal / base)))] +
conversion;
decimal = Math.floor(decimal / base);
}
return (base < 11) ? parseInt(conversion) : conversion;
}
var n = 123456;
n.toBase(62); // returns: "w7e"
这篇关于将数字转换为尽可能短的字符串,同时保留唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!