System.out.println("Before exchange:");
System.out.println("a = " + a);
System.out.println("b = " + b);
// routine to exchange a, b
...
System.out.println("After exchange:");
System.out.println("a = " + a);
System.out.println("b = " + b);
==================================
// routine to exchange a, b
...
直接:
int tmp = a;
a = b;
b = a;
不用中间量:
a = a + b;
b = a - b;
a = a - b;
不用中间量且不担心溢出:使用 bitwise Xor
a = a ^ b;
b = a ^ b;
a = a ^ b;
a=a+b;
b=a-b;
a=a-b;
int temp = a;
a = b;
b = temp;
楼上两种方法都可以,一种是借助中间变量temp,另一种不用中间变量,也有的面试题要求必须不使用中间变量的
借口借口借口就共和国