簡體   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