gpt4 book ai didi

java - (i == -i && i != 0) 的 i 值在 Java 中返回 true

转载 作者:IT老高 更新时间:2023-10-28 11:26:33 26 4
gpt4 key购买 nike

我有以下 if 条件。

if (i == -i && i != 0)

i 的什么值会在 Java 中针对这个条件返回 true

考虑到 two's complement,我无法想到 i 的任何此类值Java 中的符号。

我也希望得到这个条件的任何答案的代数证明(在 Java 的上下文中)?

最佳答案

唯一适用的 int 值是 Integer.MIN_VALUE

这是因为整数使用 two's complement way 取反。 .

使用

System.out.println(Integer.toBinaryString(Integer.MIN_VALUE));

你看到 Integer.MIN_VALUE

10000000000000000000000000000000

取负值是通过首先交换01,得到

01111111111111111111111111111111

并通过添加 1,得到

10000000000000000000000000000000

正如您在我提供的链接中看到的那样,维基百科提到了负数最多的问题,并指定它是唯一的异常(exception):

The most negative number in two's complement is sometimes called "the weird number," because it is the only exception.

当然,如果将 Long.Min_Value 存储在 long 变量中,也会出现同样的现象。

请注意,这只是由于在 Java 中对整数的二进制存储所做的选择。例如,另一个(坏)解决方案可能是通过简单地更改最高有效位并让其他位保持不变来否定,这可以避免 MIN_VALUE 的这个问题,但会产生 2 个不同的 0 值和复杂的二进制算术(例如,您将如何递增?)。

关于java - (i == -i && i != 0) 的 i 值在 Java 中返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17781150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com