繁体   English   中英

如何将 Integer.MIN_VALUE 转换为正长?

[英]How do you convert Integer.MIN_VALUE to a positive long?

我正在尝试将其转换为正长,但仍打印为负数。 当我使用其他负整数时,它可以工作但 Integer.MIN_VALUE

 if(num == Integer.MIN_VALUE){
           long number = -num;
           System.out.println(number);
       }

long num = -num; 执行为:

  1. 取 int num ,并否定它; 它仍然是一个int 换句话说,它仍然是Integer.MIN_VALUE - 因为这是所有 2^31 个 em 中没有正等值的一个负数,因为0在事物的正面“占用空间”。

  2. Then, take the number we now have (still Integer.MIN_VAUE , because -Integer.MIN_VALUE is still Integer.MIN_VALUE ), and silently cast it to a long , because that's a widening (safe) conversion, so java will just inject the cast为你。

解决方法是先转换为 long然后否定它:

任何一个:

long number = num;
number = -number;

或在一个 go 中:

long number = -((long) num);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM