(1)借助第三个变量
package HelloWorld;
public class CommutatioNumber {
public static void main(String[] args) {
int a=5,b=6;
System.out.println("a="+a+";b="+b);
int temp;
temp=a;
a=b;
b=temp;
System.out.println("a="+a+";b="+b);
}
}
(2)使用位运算符
package HelloWorld;
//异或性质:运算连续两次值不变
public class CommutatioNumber {
public static void main(String[] args) {
int a=5;//101
int b=6;//110
System.out.println("a="+a+";b="+b);
a=a^b; // 011:3
b=a^b; //011^110=101:5
a=a^b; //011^101=110:6
System.out.println("a="+a+";b="+b);
}
}
(3)使用几何数轴
package HelloWorld;
// 数轴表示 a-b 求差,最小值+1
public class CommutatioNumber {
public static void main(String[] args) {
int a=5;
int b=6;
System.out.println("a="+a+";b="+b);
b=b-a;
a=b+a;
b=a-b;
System.out.println("a="+a+";b="+b);
}
}