在博文中http://www.cnblogs.com/cysolo/p/3539210.html看到不借助第三个变量实现变量互换。
代码如下:
1 import java.util.Scanner; 2 3 public class VariableExchange { 4 public static void main(String[] args){ 5 System.out.println("请输入变量A的值"); 6 Scanner scanner=new Scanner(System.in); 7 long A=scanner.nextLong(); 8 System.out.println("请输入变量B的值"); 9 Scanner scannerB=new Scanner(System.in); 10 long B=scannerB.nextLong(); 11 System.out.println("A="+A+"\t"+"B="+B); 12 System.out.println("执行变量互换..."); 13 A=A^B; 14 B=B^A; 15 A=A^B; 16 System.out.println("A="+A+"\t"+"B="+B); 17 } 18 }
其实现是巧用了异或运算。
其原理:
a = a ^
b;
b = b ^
a;
a = a ^
b;
a1=a^b
b=a1^b=(a^b)^b=a
a=a1^b
=a1^(a1^b)=a1^a1^b=b
1 Scanner sc = new Scanner(System.in); 2 int i = sc.nextInt();
例2:
1 Scanner sc = new Scanner(new File("myNumbers")); 2 while (sc.hasNextLong()) { 3 long aLong = sc.nextLong(); 4 }
详细用法查看api文档。
原文:http://www.cnblogs.com/harry881100/p/3540117.html