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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP