@[toc]
方式一:采用中间变量
采用中间变量C,来承接a的值,再将a的值设置为b,最后将中间变脸c的值设置到b中。
int a = 10;
int b = 20;
int c = a;
a = b;
b = c;
System.out.println("a=:" + a);
System.out.println("b=:" + b);
输出结果为
a=:20
b=:10
方式二:普通加法求和方式
原理:
为了方面说明,将a,b值,赋值给c,d。
int c = a;
int d = b;
计算
d = a + b = 30;
c = d - c = (a + b) - a = 20;
d = d - c = (a + b) - a = 10;
代码:
int a = 10;
int b = 20;
b = a + b;
a = b - a;
b = b - a;
System.out.println("a=:" + a);
System.out.println("b=:" + b);
计算结果为:
a=:20
b=:10
方式三:采用异或形式计算
性质:
对给定的数A,用同样的运算因子(B)作两次异或运算后仍得到A本身(A ^ B ^ B = A)
int a = 10;
int b = 20;
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("a=:" + a);
System.out.println("b=:" + b);
结果为:
a=:20
b=:10