#include <iostream>using namespace std;//把指定的位置為0或者1。int Grial(int x, int n, int flags){ if (flags == 0) { x &= (~(0x1 << (n - 1))); } else { x |= (0x1 << (n - 1)); } return x;}int main(){ cout << Grial(15,5,1); return 0;}
#include <iostream>using namespace std;//成對出現的數組中找出唯一一個只出現一次的那個數。//按位異或相異為1,相同為0。int Grial(int a[],int n){ int i; int count = 0; for (i=0;i<n;i++) { count ^= a[i]; } return count;}int main(){ int a[] = { 1, 1, 6, 3, 3, 8, 8, 6, 10 }; cout << Grial(a,9)<<endl; return 0;}
#include <iostream>using namespace std;//求成對出現的數組中只出現一次的兩個不重複的數字。int index(int x)//求第一次出現1的下標位置。{ int count = 0; while (x) { count++; if (x & 0x1 == 1) { return count; } x >>= 1; }}bool test(int x,int y)//判斷指定的y位是不是1。{ return ((x & (0x1<<(y-1)))) != 0;}void Grial(int a[],int n){ int i = 0; int count = 0; int number1=0;//儲存第一個數。 int number2=0;//儲存第二個數。 int *Adata = new int[n]; int *Bdata = new int[n]; int k1 = 0; int k2 = 0; for (; i < n; i++) { count ^= a[i]; } i = index(count); for (int j = 0; j < n; j++)//此處將數組分成兩個部分。 { if (test(a[j], i) == true) { Adata[k1++] = a[j]; } else { Bdata[k2++] = a[j]; } } for (i = 0; i < k1; i++) { number1 ^= Adata[i]; } for (i = 0; i < k2; i++) { number2 ^= Bdata[i]; } cout << number1 << endl; cout << number2 << endl;}int main(){ int a[] = {4,4,6,82,8,3,8,3,6,1070}; Grial(a, 10); return 0;}