1. 异或
1) Single Number
a^a = 0, a^0 = a
所以出现两次的整数异或得到0,只出现一次的数异或0得到它本身。
2. 综合
1) Single Number II
如何记录目前出现一次,两次,三次的整数呢?
用三个变量one,two,three分别记录出现一次,两次,三次的数字。
一个变量第一次出现时,只记录到one中;第二次出现时,记录到two中,从one中删除;第三次出现时,在two中,记录到one中,记录到three中,然后从one和two中删除。
所以最后保存在one中的就是所求的唯一出现一次的数。
for(i=0;i<n;i++)
{
two ^= (one&A[i]); // two stores all the bits(=1) appear twice
one ^= A[i]; // one stores all the bits(=1) appear once
three = one&two; // three stores all the bits appear three times
one &= (~three); // clear the bits in one and two which appear three times
two &= (~three);
}