forked from geekxh/hello-algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
47 lines (43 loc) · 992 Bytes
/
Solution.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
/**
* @author Anonymous
* @since 2019/12/10
*/
class Solution {
/**
* 求数组中只出现一次的两个数字
*
* @param nums 数字
* @return 两个数字组成的数组
*/
public int[] findNumsAppearOnce(int[] nums) {
if (nums == null || nums.length < 2) {
return null;
}
int xorRes = 0;
for (int e : nums) {
xorRes ^= e;
}
int[] res = new int[2];
int index = indexOf1(xorRes);
for (int e : nums) {
if (isBit1(e, index)) {
res[0] ^= e;
} else {
res[1] ^= e;
}
}
return res;
}
private int indexOf1(int val) {
int index = 0;
while ((val & 1) == 0) {
val = val >> 1;
++index;
}
return index;
}
private boolean isBit1(int val, int index) {
val = val >> index;
return (val & 1) == 1;
}
}