目录
1.借用第三个变量:
交换变量a和变量b中的值(新定义一个int类型的变量c):
int a = 5;
int b = 4;
int c;
c = a;
a = b;
b = c;
System.out.println(a); //4
System.out.println(b); //5
2.不借用第三个变量,
通过乘除操作实现两个数互换:
int a = 5;
int b = 4;
a = a + b;
b = a – b;
a = a – b;
System.out.println(a); //4
System.out.println(b); //5
3.采用异或操作符:
int a = 5;
int b = 4;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println(a); //4
System.out.println(b); //5
版权声明:本文为chen_kai_fa原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。