Single Number I, all twice except one single
int singleNumber(vector<int> &A) {
// write your code here
int res = 0;
for(int i=0;i<A.size();i++){
res = res^A[i];
}
return res;
}
Single Number II All numbers occurs triple times except one
int singleNumberII(vector<int> &A) {
// write your code here
int ones=0,twos=0,threes=0;
for(int i=0;i<A.size();i++){
twos |= ones&A[i];
ones ^= A[i];
threes = ones&twos;
ones = ~threes & ones;
twos = ~threes & twos;
}
return ones;
}
Single Number III all twice numbers, except two single Number
vector<int> singleNumberIII(vector<int> &A) {
// write your code here
int x = 0;
for(int i=0;i<A.size();i++)
x^=A[i];
int rightmostbit = x&~(x-1);
int one=0,two=0;
vector<int> res;
for(int i=0;i<A.size();i++){
if(A[i]&rightmostbit)
one^=A[i];
else
two^=A[i];
}
if(one<two)
res = {one,two};
else
res = {two,one};
return res;
}