有两个整形变量
int a=2;
int b=5;
现要交换a和b的值。
常用的方法:定义一个中间变量,由这个变量暂时保存交换的值。
int temp=a;
a=b;
b=temp;
System.out.println("a="+a);
System.out.println("b="+b);
但这种方法引入的第三变量,增大了内存开销,所以还有另外两种不需要中间变量的交换方法。
加减法(算数运算法):
a=a+b;
b=a-b;//b=a-b=(a+b)-b=a
a=a-b;//a=a-b=(a+b)-b=(a+b)-a=b
System.out.println("a="+a);
System.out.println("b="+b);
通过简单的加减运算便交换了两个变量的值。
异或法:
a=a^b;
b=a^b;
a=a^b;
/**
* a=a^b 0010^0101=0111
* b=a^b 0111^0101=0010
* a=a^b 0111^0010=0101
*/
System.out.println("a="+a);
System.out.println("b="+b);
通过三次连续的异或便实现了交换
完整代码:
public static void main(String[] args) {
int a=2;
int b=5;
//常用方法:引入中间变量
int temp=a;
a=b;
b=temp;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("-------------");
//加减法
a=a+b;
b=a-b;//b=a-b=(a+b)-b=a
a=a-b;//a=a-b=(a+b)-b=(a+b)-a=b
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("-------------");
//异或的方法
a=a^b;
b=a^b;
a=a^b;
/**
* a=a^b 0010^0101=0111
* b=a^b 0111^0101=0010
* a=a^b 0111^0010=0101
*/
System.out.println("a="+a);
System.out.println("b="+b);
}
运行输出: