Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

What's your answer to this interview question?

One array, excluding one number, all other numbers in the array appear in pair. How to find the position of the number which is not in pair. For example, an array of numbers ……102,102,2,2,44,44,99,23,23,11,11 ……. The number 99 is not in pair. One more question, if the paired numbers are not adjacent to each other, i.e. an array of [102,32,99,32,45,102,45,67,67,100,100], how do you find the position of 99?

1 ANSWER



2

Use exclusive or to find the number which is not in pair. Then find the position of the number in the array. The code for finding the number which is not in pair is:

int a[11] = {102,102,2,2,44,44,99,23,23,11,11};
int result = 0;
for(int i=0; i<11; i++)
{
result ^= a[i];
}

cout<<result<<endl; //Will echo 99

 

 

  REPLY  Posted by at 2012-06-19 12:05:59

POST ANSWER


Sorry! You need to login first to post answer.

OR

Login with Facebook Login with Twitter


Back to top