两个 int 类型变量 互换数值 (无第三变量)
程序员文章站
2022-06-17 13:34:05
...
/** 同时交换(很巧妙的算法)*/ public static void main(String[] args) { int a = 5; int b = 4; b = a + 0 * (a = b); System.out.println(a + ":" + b); } /** 亦或 --类似2进制-- (最快的算法)*/ public static void main(String[] args) { int a = 5; int b = 4; a = a ^ b; b = b ^ a; a = a ^ b; System.out.println(a + ":" + b); } /** 数值相加减交换法*/ public static void main(String[] args) { int a = 5; int b = 4; a = a + b; b = a - b; a = a - b; System.out.println(a + ":" + b); } /** 数值相乘除交换法(不推荐)除数为0时会抛出异常*/ public static void main(String[] args) { int a = 5; int b = 4; if (a != 0)// 注意:此处a为除数 { a = a * b; b = a / b; a = a / b; } else { a = b; b = 0; } System.out.println(a + ":" + b); } //有更妙的算法一起交流