题目:
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?
按位进行统计操作,方法是参考博客 http://blog.csdn.net/kenden23/article/details/13625297 解答很到位,mark一下!
疑惑点:为什么 if(A[j]&d) 这个不能换成 if(A[j] & d!=0)?
C++解答:
class Solution {
public:
int singleNumber(int A[], int n) {
if(n==1)
return A[0];
int res = 0;
for(int i=0; i<32; i++)
{
int c = 0, d = 1<<i;
for(int j = 0; j<n; j++)
{
if(A[j]&d)
c++;
}
if(fmod(c,2))
res = res|d;
}
return res;
}
};