Java返回一个数值的相反数的几种方式.

方法一:直接在变量前加-

public class Demo1 {
    public static void main(String[] args) {
        System.out.println(opposite(2147483647));
    }

    public static int opposite(int number) {
        return -number;
    }
}

方法二:变量值 * -1

public static int opposite(int number) {
	return -1 * number;
}

方法三:0-变量值

public static int opposite(int number) {
	return 0 - number;
}

方法四:使用Math.negateExact方法

public static int opposite(int number) {
	return Math.negateExact(number);
}

你可能感兴趣的:(技术随笔,java,开发语言)