-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathFindNumAppearOnce40.java
More file actions
66 lines (59 loc) · 1.49 KB
/
FindNumAppearOnce40.java
File metadata and controls
66 lines (59 loc) · 1.49 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
package com.so;
/**
* 第40题
* 一个整型数组里除了两个数字之外,其他的数字都出现了两次,找出这两个只出现了一次的数字
*
* @author qgl
* @date 2017/08/16
*/
public class FindNumAppearOnce40 {
/**
* 找出只出现了一次的数
* @param array
* @return
*/
public static int[] findNumAppearOnce(int[] array) {
int[] onceNumber = new int[2];
if (array == null) {
return null;
}
int number = 0;
for (int i : array) {
number ^= i;
}
int index = findFirstBitIs1(number);
for (int i : array) {
// 第index位是0的数,即第一个数
if (isBit1(i, index)) {
onceNumber[0] ^= i;
} else {
// 第index位是1的数,即第二个数
onceNumber[1] ^= i;
}
}
return onceNumber;
}
/**
* 获取二进制中最右边是1的位置
* @param number
* @return
*/
private static int findFirstBitIs1(int number) {
int indexBit = 0;
while ((number & 1) == 0) {
number = number >> 1;
++indexBit;
}
return indexBit;
}
/**
* 判断从右边起,第index位是不是0
* @param number
* @param index
* @return
*/
private static boolean isBit1(int number, int index) {
number = number >> index;
return (number & 1) == 0;
}
}