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+ 观看次数

开启你的 职业生涯

完成课程即可获得认证

立即开始
广告