# Single Number

## Tricky bit manipulation

I have no idea at first, and search for the answer. The solution is using a tricky bit manipulation of `XOR`

.

`XOR`

will set same bit to `0`

, otherwise `1`

. so if a number appear even number times, `XOR`

will erase it.

e.g.

`[1,2,3,4,1,2,3]`

in binary form of

```
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 0 0 1
0 0 1 0
0 0 1 1
count 0 and 1
0 1 4 4
```

then remove the even number in `0 1 4 4`

to `0`

. the number becomes `0 1 0 0`

in decimal form (4).

### Source code *Read on Github*

```
1 public class Solution {
2 public int singleNumber(int[] A) {
3 // Note: The Solution object is instantiated only once and is reused by each test case.
4 if (A.length == 1) return A[0];
5 int s = A[0];
6
7 for(int i = 1; i< A.length; i++)
8 s ^= A[i];
9
10 return s;
11
12 }
13 }
```