Java 程式將正整數轉換為負數,將負數轉換為正數


要將正整數轉換為負數並反之亦然,請使用按位取反運算子。

讓我們首先初始化一個正整數 −

int positiveVal = 200;

現在,讓我們將其轉換為負數 −

int negativeVal = (~(positiveVal - 1));

現在,假設我們有以下負整數 −

int negativeVal = -300;

以下內容將負數轉換為正整數 −

positiveVal = ~(negativeVal - 1);

示例

 線上演示

public class Demo {
   public static void main(String[] args) throws java.lang.Exception {
      int positiveVal = 100;
      int negativeVal = (~(positiveVal - 1));
      System.out.println("Result: Positive value converted to Negative = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Actual Positive Value = "+positiveVal);
      negativeVal = -200;
      System.out.println("Actual Negative Value = "+negativeVal);
      positiveVal = ~(negativeVal - 1);
      System.out.println("Result: Negative value converted to Positive = "+positiveVal);
   }
}

輸出

Result: Positive value converted to Negative = -100
Actual Positive Value = 100
Actual Negative Value = -200
Result: Negative value converted to Positive = 200

更新於: 30-7-2019

9K+ 觀看次數

開啟你的 職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.