两个变量a,b 交换其数值的三种方法

1, c=a; a=b; b=c;

2,

n = n + m;//如果n和m的值非常大,容易超出int范围。

m = n - m;

n = n - m;

3,

n = n ^ m;

m = n ^ m;//(n^m)^m;

n = n ^ m;//n ^ (n ^ m)

注: 上述方法在执行多次后,第二种方法效率会高一些,在只执行一次或者少次的情况下第一,三两种方法反而效率高一些。所以第一种方法在少量运算的情况下,比较好。在多次的时候第二种比较好。

 1 import java.util.Random;
 2 
 3 public class Day042
 4 {
 5     public static void main(String[] args)
 6     {
 7     }
 8 
 9     static void testEfficiency1()
10     {
11         long l1 = System.currentTimeMillis();
12         for (int i = 0; i < 10000; i++)
13         {
14             Random r = new Random(System.currentTimeMillis());
15             int[] arr = new int[2];
16             arr[0] = (int) (Math.random() * 100);
17             arr[1] = (int) (Math.random() * 100);
18             // System.out.println(Arrays.toString(arr));
19             arr[0] = arr[0] ^ arr[1];
20             arr[1] = arr[0] ^ arr[1];
21             arr[0] = arr[0] ^ arr[1];
22         }
23         long l2 = System.currentTimeMillis();
24         System.out.println(l2 - l1);
25     }
26     static void testEfficiency2()
27     {
28         long l1 = System.currentTimeMillis();
29         for (int i = 0; i < 10000; i++)
30         {
31             Random r = new Random(System.currentTimeMillis());
32             int[] arr = new int[2];
33             arr[0] = (int) (Math.random() * 100);
34             arr[1] = (int) (Math.random() * 100);
35             // System.out.println(Arrays.toString(arr));
36             int t = arr[0];
37             arr[0] = arr[1];
38             arr[1] = t;
39         }
40         long l2 = System.currentTimeMillis();
41         System.out.println(l2 - l1);
42     }
43 
44     static void testEfficiency3()
45     {
46         long l1 = System.currentTimeMillis();
47         for (int i = 0; i < 10000; i++)
48         {
49             Random r = new Random(System.currentTimeMillis());
50             int[] arr = new int[2];
51             arr[0] = (int) (Math.random() * 100);
52             arr[1] = (int) (Math.random() * 100);
53             // System.out.println(Arrays.toString(arr));
54             arr[0] = arr[0] + arr[1];
55             arr[1] = arr[0] - arr[1];
56             arr[0] = arr[0] - arr[1];
57         }
58         long l2 = System.currentTimeMillis();
59         System.out.println(l2 - l1);
60     }
61 }

 

转载于:https://www.cnblogs.com/linson0116/p/3502367.html

你可能感兴趣的:(两个变量a,b 交换其数值的三种方法)