# 初阶查找单身狗

## C语言代码实现

``````int singleNumber(int* nums, int numsSize){
int ret = 0;
for(int i = 0;i<numsSize; i++)
{
ret^=nums[i];
}
return ret;
}
``````

## Java代码实现

``````class Solution {
public int singleNumber(int[] nums) {
int ret = 0;
for(int i = 0; i<nums.length; i++) {
ret^=nums[i];
}

return ret;
}
}
``````

# 进阶找单身狗

leedcode之只出现一次的数字（进阶）

## C语言代码实现

``````/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* singleNumber(int* nums, int numsSize, int* returnSize){
//动态开辟一个两个元素为0的数组，用来存放两个单身狗
int* ans = (int*)calloc(2,sizeof(int));
int ret = 0;
for(int i =0 ;i<numsSize; i++)
{
ret^=nums[i];
}
//pos用来记录ret中哪个二进制位为1
int pos = 0;
for(int i = 0; i<32; i++)
{
if((ret>>i)&1 == 1)
{
pos = i;
break;
}
}
for(int i = 0; i<numsSize; i++)
{
if((nums[i] >> pos)&1 == 1)
{
ans[0]^=nums[i];
}
else
{
ans[1]^=nums[i];
}
}

*returnSize = 2;
return ans;
}
``````

## Java代码实现

``````class Solution {
public int[] singleNumber(int[] nums) {
int[] ans = new int[]{0,0};
int ret = 0;
for(int i  =0; i<nums.length; i++) {
ret^=nums[i];
}
int pos = 0;
for(int i = 0; i<32; i++) {
if(((ret>>i)&1) == 1) {
pos = i;
break;
}
}
for(int i = 0; i<nums.length; i++) {
if(((nums[i]>>pos)&1) == 1) {
ans[0]^=nums[i];
}else{
ans[1]^=nums[i];
}
}
return ans;
}
}
``````

THE END

)">