问题:链接
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
利用运算,所有位加,能除尽3说明多余的一个数该位为0,否则为1.
参考:
代码:http://blog.csdn.net/kenden23/article/details/13625297
http://www.cnblogs.com/daijinqiao/p/3352893.html
class Solution {
public:
int singleNumber(int A[], int n) {
int sum[32] = {0};
int i,j,temp,result;
result = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j<32; j++)
{
sum[j] += (A[i]>>j)&0x01;
}
}
for(j = 0; j < 32; ++j)
{
if(sum[j]%3 == 0)
temp = 0;
else
temp = 1;
result += (temp<<j);
}
return result;
}
};