# Easiest way to solve by using bit manipulation.

• Logic: XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.
A ^ A = 0 and A ^ B ^ A = B.

``````class Solution {
public:
int singleNumber(int A[], int n) {
int result=A[0];
for(int i=1;i<n;i++)
{
result= result^A[i];  /* Get the xor of all elements */
}
return result;
}
};``````

• How could you translate that code into Python? What if you need to implement your own XOR for Python's arbitrary precision integer?

• Here is the Python form of XOR:
a ^= b
and to complete the solution you need add only 4 lines to the given code :)

• It is a really smart solution.

• Great! Thanks!

• Nice! Thanks for sharing.

• Great one!
thanks!

• What a master mind

• I dont quite get that, what if the array is {1,1,1,2}
you method is returning wrong resullt

• The question is specifying that every number appears exactly twice except for that single number which appears only once that you are looking for.

• "i" and "result" are extra spaces.

``````class Solution {
public:
int singleNumber(int A[], int n) {
while (--n){
A[n-1] ^= A[n];
}
return A[0];
}
};``````

• "n" is also extra space

• Kudos, quite a nice work!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.