-
Notifications
You must be signed in to change notification settings - Fork 0
/
SingleNumber.java
57 lines (49 loc) · 1.24 KB
/
SingleNumber.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
package leetcode.leetcodes;
import org.junit.Test;
/*
* Given an array of integers, every element appears twice except for one. Find that single one.
* Using XOR
*
* Given an array of integers, every element appears three times except for one. Find that single one.
* Get each bit number of the binay number, add them and divide by three
*/
public class SingleNumber {
public int singleNumberInDouble(int[] A) {
int result = A[0];
for (int i = 1; i < A.length; i++) {
result ^= A[i];
}
return result ^ 0;
}
public int singleNumberInTriple(int[] A) {
int number = 0;
int base = 1;
for (int i = 0; i < 32; i++) {
int sum = 0;
int bitComparator = base << i;
for (int j = 0; j < A.length; j++) {
sum += (A[j] & bitComparator) == 0 ? 0 : 1;
}
sum %= 3;
number |= sum << i;
System.out.println("sum : " + sum + " number: " + number);
}
return number;
}
/* Helper Function */
// public int getBitNumber(String original, int bit) {
// int length = original.length();
//
// if (bit > length - 1) {
// return 0;
// }
//
// return Character.getNumericValue(original.charAt(length - 1 - bit));
//
// }
@Test
public void test() {
int[] A = { 1, 2, 2 };
System.out.println(singleNumberInDouble(A));
}
}