-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindNumsAppearOnce.java
More file actions
82 lines (66 loc) · 2.08 KB
/
FindNumsAppearOnce.java
File metadata and controls
82 lines (66 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
public class FindNumsAppearOnce {
//一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
//
//对于位运算有:b&1=b;b^0=b;
//对于数运算:x^0=x;x^x=0;对于b为00001,00010.....当 x&b==b时可得该位数为1;对于全为1的一个数n有 n&x=x;
public static void main(String args[]) {
int array[] = {2, 4, 4, 5, 3, 3, 9, 9};
int num1[] = {0};
int num2[] = {0};
FindNumsAppearOnce.FindNumsAppearOnce(array, num1, num2);
System.out.println(num1[0]);
System.out.println(num2[0]);
}
//todo
//test
public static void FindNumsAppearOnce(int[] array, int num1[], int num2[]) {
///解题思路:根据一个数与0的异或结果为本身,把所有的数进行异或,的到的是不同数的异或,根据易货 的结果的1的位置进行分组
if (array == null || array.length < 2)
return;
int temp = 0;
for (int i = 0; i < array.length; i++)
temp ^= array[i];
int indexOf1 = findFirstBitIs(temp);
for (int i = 0; i < array.length; i++) {
if (isBit(array[i], indexOf1))
num1[0] ^= array[i];
else
num2[0] ^= array[i];
}
}
//00
public static int findFirstBitIs(int num) {
int indexBit = 0;
while (((num & 1) == 0) && (indexBit) < 8 * 4) {
num = num >> 1;
++indexBit;
}
return indexBit;
}
public static boolean isBit(int num, int indexBit) {
num = num >> indexBit;
return (num & 1) == 1;
}
public static void FindNumsAppearO(int [] array,int num1[] , int num2[]){
Integer s=new Integer(6);
int count =0;
int flag=0;
for(int i=0;i<array.length;i++){
for(int j=0;j<array.length;j++){
if(i!=j){
if(array[i]==array[j]){
flag=1;
}
}
}
if(flag==0&&count==0){
num1[0]=array[i];
count++;
}
if(flag==0&&count==1){
num2[0]=array[i];
}
flag=0;
}
}
}