Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created January 16, 2014 09:44
Show Gist options
  • Save junjiah/8452266 to your computer and use it in GitHub Desktop.
Save junjiah/8452266 to your computer and use it in GitHub Desktop.
class Solution {
public:
// single number i
int singleNumber(int A[], int n) {
int result = 0;
for (int i; i<n ;++i)
result = (result ^ A[i]);
return result;
}
// single number ii, like base 3 xor
int singleNumber(int A[], int n) {
int bitSize = CHAR_BIT * sizeof(int);
char *bits = new char[bitSize];
for (int i=0; i<bitSize; ++i) bits[i] = 0;
for (int i=0; i<n; ++i) {
for (int j=0; j<bitSize; ++j)
bits[j] = (bits[j] + ( (A[i] >> j) & 1 )) % 3;
}
int result = 0;
for (int i=0; i<bitSize; ++i) {
result |= ( ((int)(bits[i] != 0)) << i );
}
delete[] bits;
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment