1.2题解:如何找数组中唯一成对的那个数(位运算)

&(与)两边都为1则结果为1,否则为0
0&0 = 0,0&1 = 0,1&0 = 0, 1&1 = 1

|(或)两边都为0则结果为0,否则为1
0|0 = 0,0|1 = 1,1|0 = 1,1|1 = 1

~(非/取反)
取反加1

^(异或)只有一边为1结果才为1,否则为0
0^0 = 0,0^1 = 1,1^0 = 1,1^1 = 0

<<(左移乘2n)
11<<n  结果为11*(n*2)

>>(右移除2n)

44>>n  结果为44/(n*2)

%(取余)
3%2 余 1,2%3 余 2

/(取整)
3/2 商 1,2/3 商 0

 1 public class One_2如何找数组中唯一成对的那个数 {
 2     public static void main(String[] args) {
 3         int N = 11;
 4         int[] arr = new int[N];
 5         for (int i = 0; i < N-1; i++){
 6             arr[i] = i+1;
 7         }
 8         
 9         //最后一个数,是随机数(长度为11的数组,最后一个元素下标应该为10)
10         arr[arr.length-1] = new Random().nextInt(N)+1;//Random().nextInt()会产生一个0到指定数N的随机数不包含N,+1代表从1到指定数字
11         //随即下标0~10之间
12         int index = new Random().nextInt(N);
13         swap(arr, index, arr.length-1);
14         for (int i = 0; i < N; i++){
15             System.out.print(arr[i] + " ");
16         }
17         int x1 = 0;
18         for (int i = 1; i < N; i++){
19             x1 = (x1^i);
20         }
21         System.out.println(x1);
22         for (int i = 0; i < N; i++){
23             x1 = x1^arr[i];
24         }
25         System.out.println(x1);
26     }
27     public static void swap(int[] arr,int x,int y){
28         int temp;
29         temp = arr[x];
30         arr[x] = arr[y];
31         arr[y] = temp;
32     }
33 }

 

posted @ 2019-11-30 21:43  GrnLeaf  阅读(207)  评论(0编辑  收藏  举报