forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test40.java
61 lines (50 loc) · 1.46 KB
/
Test40.java
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
/**
* Author: Íõ¿¡³¬
* Date: 2015-06-14
* Time: 09:52
* Declaration: All Rights Reserved !!!
*/
public class Test40 {
public static int[] findNumbersAppearanceOnce(int[] data) {
int[] result = {0, 0};
if (data == null || data.length < 2) {
return result;
}
int xor = 0;
for (int i : data) {
xor ^= i;
}
int indexOf1 = findFirstBit1(xor);
for (int i : data) {
if (isBit1(i, indexOf1)) {
result[0] ^= i;
} else {
result[1] ^= i;
}
}
return result;
}
private static int findFirstBit1(int num) {
int index = 0;
while ((num & 1) == 0 && index < 32) {
num >>>= 1;
index++;
}
return index;
}
private static boolean isBit1(int num, int indexBit) {
num >>>= indexBit;
return (num & 1) == 1;
}
public static void main(String[] args) {
int[] data1 = {2, 4, 3, 6, 3, 2, 5, 5};
int[] result1 = findNumbersAppearanceOnce(data1);
System.out.println(result1[0] + " " + result1[1]);
int[] data2 = {4, 6};
int[] result2 = findNumbersAppearanceOnce(data2);
System.out.println(result2[0] + " " + result2[1]);
int[] data3 = {4, 6, 1, 1, 1, 1};
int[] result3 = findNumbersAppearanceOnce(data3);
System.out.println(result3[0] + " " + result3[1]);
}
}