-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleNumber.cpp
More file actions
48 lines (38 loc) · 908 Bytes
/
Copy pathSingleNumber.cpp
File metadata and controls
48 lines (38 loc) · 908 Bytes
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
class Solution {
public:
int singleNumber(int A[], int n) {
int tmp = 0;
for (int i = 0; i < n ; i++)
{
tmp ^= A[i];
}
return tmp;
}
int singleNumberII(int A[], int n) {
int bitcount[32] = {0};
int sign = 0;
int tmp = 0;
for (int i = 0; i < n; i++)
{
tmp = A[i];
if (tmp < 0)
{
tmp = -tmp;
sign = (sign + 1) % 3;
}
for (int j = 0; j < 32; j++)
{
bitcount[j] = (bitcount[j] + (tmp & 0x1)) % 3;
tmp >>= 1;
}
}
int res = 0;
tmp = 1;
for (int i = 0; i < 32; i++)
{
res += (tmp * bitcount[i]);
tmp <<= 1;
}
return sign==0 ? res: res*-1;
}
};