将字符串转换为数字以进行比较

发布于 2024-11-18 02:05:25 字数 218 浏览 2 评论 0原文

我需要你帮助解决一个小问题。

是否有可能(在 Java 或抽象解决方案中)将任意字符串转换为具有以下属性的整数:字母顺序也适用于整数?

例子: 房子<树<动物园按字母顺序排列。

我想将这些字符串转换为整数,以便排序也可用。重要的是,具体的字符串之前是未知的。这意味着它应该是一个独特的转变。

我希望有人能帮助我。

问候, 迈克尔

I need your help with a small problem.

It there a possibility (in Java or an abstract solution) to transform a arbitrary String into an Integer with the property, that the alphabetically ordering does also work with the Integer?

Example:
House < Tree < Zoo in alphabetically order.

I would like to transform those Strings into Integer, so that the ordering is also available. Important is, that the concrete Strings are not known before. That means it should be a unique transformation.

I hope someone can help me.

Regards,
Michael

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶 2024-11-25 02:05:25

不,这是不可能的。假设您有两个代表 1 和 2 的字符串。您始终可以创建另一个按字母顺序排列在它们之间的字符串,例如,

aa  = 1
ab  = 2
aaa = ???

如果您知道正在处理的字符串有最大长度,那么这是可能的。例如,假设您的字符串长度 <= 3。取一个字符串 abc,并将每个字母转换为数字,其中 A = 1,B = 2,...,Z = 26。如果字符串小于 3字符长,末尾的空白处填零。则其值为:

(a * 27 * 27) + (b * 27) + c

则:

aa  = 756
ab  = 783
aaa = 757

No, it's not possible. Let's say you have two strings which represent 1 and 2. You can always make another string which would fit between them alphabetically e.g.

aa  = 1
ab  = 2
aaa = ???

If you know the strings you're dealing with have a maximum length, then this is possible. For example, suppose your string has length <= 3. Take a string abc, and convert each letter to a number, where A = 1, B = 2, ..., Z = 26. If the string is less than 3 characters long, fill in the blanks at the end with zeroes. Then the value is:

(a * 27 * 27) + (b * 27) + c

Then:

aa  = 756
ab  = 783
aaa = 757
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文