Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
The trick in this problem is to use XOR
the bitwise XOR in java
0 ^ N = N
N ^ N = 0
if N is the single number
N1 ^ N1 ^ N2 ^ N2 ^…^ Nx ^ Nx ^ N
= (N1^N1) ^ (N2^N2) ^…^ (Nx^Nx) ^ N
= 0 ^ 0 ^ …^ 0 ^ N
= N
class Solution {
public int singleNumber(int[] nums) {
int res=0;
for(int i=0;i<nums.length;i++){
res ^= nums[i];
}
return res;
}
}