1 2 3 4 5 6 7 8 9 10 11 12 13 |
int singleNumber(int A[], int n) { if(n < 0) { return -1; } int result = 0; for(int i = 0; i < n; ++i) { result ^= A[i];/*1^1=0 0^0=0*/ } return result; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
int singleNumber(int A[], int n) { //一个整数的bit数,即整数字长 const int W = sizeof(int) * 8; //表示在i位出现的1的个数 int count[W]; //注意这里乘以4不要忘记了 memset(count, 0, W * 4); for(int i = 0; i < n; ++i) { for(int j = 0; j < W; ++j) { count[j] += (A[i] >> j) & 0x1; if(count[j] >= 3) { /*因为每次累加1*/ count[j] = 0; } } } int result = 0; for(int i = 0; i < W; ++i) { result += (count[i] << i); } return result; } |
与 |
或 |
非 |
异或 |
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0 |
~1 = 0
~0 = 1 |
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 =
0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
int singleNumber(int A[], int n) { int ones = 0, twos = 0, threes = 0; for(int i = 0; i < n; i++) { //已经出现两次并且再次出现 threes = twos & A[i]; //曾经出现两次的或者曾经出现一次但是再次出现的 twos = twos | (ones & A[i]); //出现一次的 ones = ones | A[i]; //当某一位出现三次后,我们就从出现两次中消除该位 twos = twos & ~threes; //当某一位出现三次后,我们就从出现一次中消除该位 ones = ones & ~threes; } //twos, threes最终都为0.ones是只出现一次的数 return ones; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
#include <iostream> using namespace std; bool IsBit1(int num, unsigned int indexBit) { num = num >> indexBit; return (num & 1); } unsigned int FindFirstBitIs1(int num) { int indexBit = 0; while ( ((num & 1) == 0) && (indexBit < 8 * sizeof(int)) ) { num = num >> 1; ++ indexBit; } return indexBit; } void FindNumsAppearOnce(int data[], int length, int *num1, int *num2) { if (data == NULL || length < 2) { return ; } int resultExclusiveOR = 0; for (int i = 0; i < length; ++i) { resultExclusiveOR ^= data[i]; } unsigned int indexOf1 = FindFirstBitIs1(resultExclusiveOR); *num1 = *num2 = 0; for (int j = 0; j < length; ++j) { if (IsBit1(data[j], indexOf1)) { *num1 ^= data[j]; } else { *num2 ^= data[j]; } } } int main() { int data[] = {2, 4, 3, 6, 3, 2, 5, 5}; int length = sizeof(data) / sizeof(data[0]); int num1, num2; FindNumsAppearOnce(data, length, &num1, &num2); cout << num1 << " " << num2 << endl; return 0; } |
【01】数组中只出现一次的数字,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/codemylife/p/3777245.html