兩值互換的3種方法html
一、最簡單的一種想法,求和相減法spa
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); } }
效果圖
.net
二、最經常使用方法,利用中間值code
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); } }
效果圖
htm
三、利用異或運算blog
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...get