//一个数字出现一次 #include<iostream> using namespace std; int once(int* a, int num) { int ret = 0; for (int i = 0; i < num; ++i) { ret ^= a[i]; } return ret; } int main() { int array[5] = { 1, 2, 2, 3, 3 }; int sum = once(array, 5); cout << sum << endl; return 0; } //两个出现一次 #include <iostream> using namespace std; int TWO(int num) { int get = 0; while (num) { if (num % 2 == 1)//返回二进制中出现的第一个一的位数 { return get; } get++; num /= 2; } return -1; } void find(int*a, int ret, int *p, int *q) { int find = 0; int pos = 0; for (int i = 0; i < ret; ++i) { find ^= a[i]; } pos = TWO(find); for (int i = 0; i < ret; ++i) { if (1 & (a[i] >> pos)) { *p ^= a[i]; } else { *q ^= a[i]; } } } int main() { int a[8] = { 1, 1, 2, 5, 3, 3, 4, 5 }; int ret = sizeof(a) / sizeof(a[0]); int num1 = 0; int num2 = 0; find(a, ret, &num1, &num2); cout << num1 << "," << num2 << endl; return 0; }
时间: 2024-11-04 19:41:59