I am a new computer science undergrad. For my assignment I need to implement isNotEqual(int x, int y) function in C by just using bitwise operators. This function will return false if x and y are equal, true otherwise. I have tried to just use x ^ y, but it couldn't pass all the test cases. My assumption was if only x and y are equal, it will return as a 0, and if they are not equal, it will return as a non-zero integer. In our first lessons, we learned that C returns non-zero values as true. To solve this problem I tried to use !(!(x ^ y)) and it worked. I can see the difference between my 2 solutions. For the second one, all the bits are converted to '1' but I don't understand why the simpler first solution doesn't work. Can someone explain why my first solution couldn't pass all the tests?
I tried:
int isNotEqual(int x, int y){
return x^y;
}
But the correct solution was:
int isNotEqual(int x, int y){
return !(!(x^y));
}
You have not shown the text of the assignment. Likely one of these things is true:
xandyare not equal and zero otherwise. In this case, you need to usereturn !! (x^y);or equivalent.xandyare not equal and zero otherwise. In this case,return x^y;is sufficient and, if the test program complains, it is improperly written.