// 程序员面试题精选100题(63)-数组中三个只出现一次的数字.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define N 5
int _tmain(int argc, _TCHAR* argv[])
{
int arr[N]={2,14,6,6,5};// 0 is wrong
int sum=0;
int dior=1;
for(int i=0;i<N;i++)
{
sum^=arr[i];
}
cout<<" in debug sum is "<<sum<<endl;
int sum1=0,sum2=0;
while((sum&dior)==1)// for three element or, if the result is 0 means that they are not all the same, so we look for the bit witch is 0,
dior=dior<<1;
cout<<" in debug dior is "<<dior<<endl;
sum1=0;sum2=0;
for (int i=0;i<N;i++)
{
if ((arr[i]&dior)==0)
{
sum1=sum1^arr[i];
}
else
{
sum2=sum2^arr[i];
}
}
cout<<" in debug sum1,2 is "<<sum1<<" "<<sum2<<" "<<endl;
//不知道怎么判断sum1,sum2哪个是一个单独的元素,哪个是两个元素的抑或,索性直接求了,sum3,sum4用于假设sum1是两个元素的和。
//如果假设错了,即sum1其实是一个元素,那么经过运算求得的sum3,sum4一定有一个是为0.因为初始时sum3,sum4有且只有一个赋值为上一步的两个运算的抑或值,
//当把所有元素分配到sum3,sum4时,原来的两个抑或的元素分别也会分配到刚才的sum3,或是sum4.这样,相当于原来的数组增加了来个元素,最后的结果只有一个单独的元素,或者在sum3,或者在sum4
int sum3=0,sum4=0;
int sum5=0,sum6=0;
int dior1=1;
while((sum1&dior1)==0)//deal with sum1,consider sum1 is the or value of two elements,so sum2 is another element beside current two. for two element, look for the bit which is 1,
dior1=dior1<<1;//reset dior
if ((sum2&dior1)==0)// if this,means offset the only element, which is just sum2
{
sum3=sum3^sum2;
}
else
{
sum4=sum4^sum2;
}
for (int i=0;i<N;i++)
{
if ((arr[i]&dior1)==0) //here must add ()
{
sum3^=arr[i];
}
else
{
sum4^=arr[i];
}
}
if ((sum3!=0)&&(sum4!=0))
{
//sum2=sum^sum3^sum4;
cout<<sum2<<" "<<sum3<<" "<<sum4<<endl;
}
int dior2=1;
while((sum2&dior2)==0)//deal with sum2,consider sum2 is the or value of two elements,so sum1 is another element beside current two.
dior2=dior2<<1;
if ((sum1&dior2)==0)// if this,means offset the only element
{
sum5=sum5^sum1;
}
else
{
sum6=sum6^sum1;
}
for (int i=0;i<N;i++)
{
if ((arr[i]&dior2)==0)
{
sum5^=arr[i];
}
else
{
sum6^=arr[i];
}
}
if ((sum5!=0)&&(sum6!=0))
{
//sum1=sum^sum5^sum6;
cout<<sum1<<" "<<sum5<<" "<<sum6<<endl;
}
system("pause");
return 0;
}
我自己的算法。看给的答案也不太简单。
有零怎么办?
不是整形怎么办?