2

Actually it's a hackerrank problem, the lonely integer. I understand the XOR logic used here. I just couldn't understand deeply the concept how is every number being processed after input. I have marked the line in code. Please help me in understanding it.

#include <iostream>
using namespace std;

int main()
{
    int n, a, c = 0, i;
    cin >> n;
    for (i = 0; i < n; i++)
    {
        cin >> a;
        c ^= a; // THIS LINE .... i WANT TO KNOW HOW IS THIS WORKING ?
        // HOW IS COMPARISON BEING CARRIED OUT HERE ?
    }
    cout << a << endl;
    return 0;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Shubham
  • 53
  • 1
  • 7
  • As a budding programmer, you might want to consider some courses. These questions you ask about would totally be covered. – Deanie May 29 '15 at 22:28
  • 1
    Why should I take a course from a single expert when I can learn from experts all over the world....Just kidding :P..... I am actually learning algorithm design using competitive programming .... Thanks for your concerns by the way. – Shubham May 29 '15 at 22:32
  • See also http://stackoverflow.com/q/6398427/ – Nemo May 29 '15 at 23:23
  • Can you describe the problem? It's not clear from the description what the goal is. – sashang Jun 17 '15 at 05:28
  • @sashang , I have got what I was looking for. I wanted to know the iterations by which c^c returns 0. – Shubham Jun 18 '15 at 18:01

1 Answers1

3

Program finds the number which is lonely, i.e. not in pair. XORing a number to itself results in 0. Using this concept all numbers are XORed one by one. A pair of number is xored and then the result is xored with another number in the input sequence and so on. At last the number which comes single will be left.
For example :

For the input 1 1 2 3 0 0 3

1 ^ 1 = 0
0 ^ 2 = 2 
2 ^ 3 = 1 
1 ^ 0 = 1
1 ^ 0 = 1
1 ^ 3 = 2  

and 2 is lonely.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Thanks for answering :).... but why/how is the left one only displaying there ? why not the one with b^b=0 are released for displaying ? – Shubham May 29 '15 at 22:27