对于正数来说,其相反数可以通过取反加1获取。对于负数来说,它的相反数可以通过减一取反获得。
示例:
public class BinaryTest {
public static void main(String[] args) {
int a = 413;
int b = -109;
System.out.println("-a = " + (~a + 1));
System.out.println("-b = " + ~(b - 1));
}
}
注意:
当一个变量的值是其类型的能表示的最小的值时,这种方式求相反数无效。
示例:
public class BinaryTest {
public static void main(String[] args) {
int num = Integer.MIN_VALUE;
System.out.println("num = " + num);
System.out.println("减1取反后:" + ~(num - 1));
}
}