Created
January 16, 2014 09:44
-
-
Save junjiah/8452266 to your computer and use it in GitHub Desktop.
solved "Single Number" I and II on LeetCode (XOR!) http://oj.leetcode.com/problems/single-number/ *and* http://oj.leetcode.com/problems/single-number-ii/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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