+ 2

Explain this code....

This code is about finding the nonrepeating element in an array using bitwise operation. Can you please explain what is exactly happening here or what that "xor" is doing here? the Code: #include<stdio.h> int main(){ int ara[] = {1,2,3,4,1,2,3}; int result, i, n = 7; result = ara[0]; for(i = 1; i < n; i++){ result = result ^ ara[i]; } printf("%d\n", result); return 0; }

27th Jan 2021, 9:37 AM
Swapnil
Swapnil - avatar
2 Answers
+ 4
0001 0010=0011 0011 0011=0000 0000 0100=0100 0100 0001=0101 0101 0010=0111 0111 0011=0100=4 if you see the above operations you will notice that XOR results in 0 when both operands have 1 at same bit place. So if we had 1 represented in bit as 0001 ,the above number when compared later to another repeating number 1 turned all bits into 0 , thereby removing the repeated character . So basically 1,2,3 nulls the other 1,2 and 3 numbers and we are left with 4!! This is what I see and can tell you but wait for better answers.
27th Jan 2021, 9:55 AM
Abhay
Abhay - avatar
+ 1
Abhay Owh thnx a lot 💖 â˜ș
27th Jan 2021, 1:21 PM
Swapnil
Swapnil - avatar