两值互换的3种方法
1、最简单的一种想法,求和相减法
public class 两值交换01 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num01 = input.nextInt();
int num02 = input.nextInt();
System.out.println("数值互换前");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
num01=num01+num02;//num01(15)=num01(10)+num02(5)
num02=num01-num02;//num02(10)=num01(15)-num02(5)
num01=num01-num02;//num01(5)=num01(15)-num02(10)
System.out.println("数值互换后");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
}
}
效果图
2、最常用方法,利用中间值
public class 两值交换02 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num01 = input.nextInt();
int num02 = input.nextInt();
System.out.println("数值互换前");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
int temp;
temp = num01;
num01 = num02;
num02 = temp;
System.out.println("数值互换后");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
}
}
效果图
3、利用异或运算
public class 两值交换03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num01 = input.nextInt();
int num02 = input.nextInt();
System.out.println("数值互换前");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
num01 = num01 ^ num02;
num02 = num01 ^ num02;
num01 = num01 ^ num02;
System.out.println("数值互换后");
System.out.println("num01=" + num01 + "," + "num02=" + num02);
}
}
效果图
若不理解异或概念,请先看看以下内容
http://blog.csdn.net/renjie_9...
http://www.cnblogs.com/Rachel...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。