位运算实现高效互换

 1 import java.util.Scanner;
 2 
 3 public class b {
 4 
 5     public static void main(String[] args) {
 6         Scanner scan = new Scanner(System.in);
 7         System.out.println("请输入A");
 8         long A = scan.nextLong();
 9         System.out.println("请输入B");
10         long B = scan.nextLong();
11         scan.close();
12         System.out.println("A=" + A + "\tB=" + B);
13         System.out.println("执行变量互换");
14         A = A ^ B;  //现在a中记录下了原a和原b每位上相同不相同的标志(0代表相同1代表不同)
15         B = B ^ A;  
16         A = A ^ B;  
17         System.out.println("A=" + A + "\tB=" + B);
18     }
19 
20 }

原来是这样的

int a,b,c;

c = a;a=b;b=c;

c一般是临时变量,临时变量增加了系统资源的消耗(常见数组排序法),使用^不需要创建临时变量c,节省资源。

猜你喜欢

转载自www.cnblogs.com/legiorange/p/9136641.html