1. Find the number which occurs once in an array while all other elements occurs twice using XOR,
CODE:
#include <iostream>
using namespace std;
int main()
{
int a[11]={1,3,9,9,3,6,7,8,7,8,1};//declaring the array//
int result=a[0];
for(int i=1;i<11;i++)
{
result=result^a[i];
}
cout<<result<<endl;
return 0;
}
OUTPUT:
NOTE: In XOR operation two same elements gives an output of 0 . Also, XOR operation is commutative and associative, so all the elements appearing twice will results in 0 giving the number which occurs once as output.
In this problem,
1^3^9^9^3^6^7^8^7^8^1
=(1^1)^(3^3)^(9^9)^6^(7^7)^(8^8) (by commutative and associative property)
=0^0^0^6^0^0
=6^0
=6 (giving the output as 6 which occurs once)


0 Comments