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