1. 一个数组中,只有两个数出现一次,其他都出现两次,找出这两个出现一次的数.(异或的运用和位操作)
int get_xor_result(int a[],int length)
{
int tem = 0;
for(int i =0; i<length; i++)
{
tem ^= a[i];
}
return tem;
}
int get_pos(int tem)
{
for(int i = 0; i<32; i++)
{
if(tem & 1 == 1)
return i;
tem >>= 1;
}
return 0;
}
int get_num(int a[],int length,int *num1,int *num2)
{
int result,pos;
result = get_xor_result(a,length);
pos = get_pos(result);
*num1 = *num2 = 0;
for(int i=0; i<length; i++)
{
if((a[i]>>pos & 1) == 1)
*num1 ^= a[i];
else
*num2 ^= a[i];
}
return 0;
}
int main(void)
{
int a[10]={1,2,3,4,5,6,4,3,2,1};
int num1,num2;
get_num(a,10,&num1,&num2);
printf("%d,%d\n",num1,num2);
printf("hello world\n");
return 0;
}
2.一个大数组中只有两个数有重复的,其他都是出现一次,找出是哪两个数?
#include <stdio.h>
#define LENGTH 10
static char array[LENGTH / 8 + 1];
void get_num(int a[], int length, int *num1, int *num2)
{
int tem = 0;
*num1 = *num2 = 0;
for (int i = 0; i < length; i++)
{
tem = (array[a[i] / 8] >> (a[i] % 8)) & 1;
if (tem != 1)
array[a[i] / 8] |= 1 << a[i] % 8;
else
{
if (*num1 == *num2)
*num1 = a[i];
else
*num2 = a[i];
}
}
}
int main()
{
int num1, num2;
int a[LENGTH] = { 1, 2, 11, 4, 11, 5, 6, 6, 7, 8 };
get_num(a, LENGTH, &num1, &num2);
printf("%d,%d\n", num1, num2);
printf("hello world\n");
return 0;
}