有一组整型数,其中除了2个数字以外的其它的数字都是俩俩成对出现的,编写程序找出这2个不成对出现的数字
函数原型:
void search_diff(int array[],int len,int* pa,int* pb);
示例:
void search_diff(int array[],int len,int* pa,int* pb);
int a=0;
int b=0;
int array[]={3,4,5,5,3,4,1,6,6,7,2,8,7,8};
search_diff(array,sizeof(array)/sizeof(*a),&a,&b);
调用后,a,b为1,2或者a,b为2,1
#include "stdafx.h"
#include <iostream>
#include <malloc.h>
using namespace std;
int first_one_bit(unsigned int v) //找到某位为1
{
int ret = 0;
while((v != 0) && (v&1) == 0)
{
v = v >> 1;
ret++;
}
return ret;
}
void search_diff(int array[],int len,int* pa,int* pb)
{
if((array != NULL) && (pa != NULL) && (pb != NULL))
{
int r = 0;
int flag =0;
for(int i=0;i<len;i++)
{
r = r^array[i]; //由于有两个落单的数,异或之后,肯定有某位为1;r = a^b;
}
flag = 1 << first_one_bit(r);
*pa = 0;
*pb = 0;
for(int i=0;i<len;i++)
{
if(array[i] & flag)
{
*pa = *pa^array[i];
}
else
{
*pb = *pb^array[i];
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a=0;
int b=0;
int array[]={3,4,5,5,3,4,1,6,6,7,2,8,7,8};
search_diff(array,sizeof(array)/sizeof(*array),&a,&b);
cout << a << " " << b << endl;
return 0;
}
打印:
1 2
请按任意键继续. . .
//来源于狄泰软件学院