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:
x and y are not equal and zero otherwise. In this case, you need to use return !! (x^y); or equivalent.x and y are not equal and zero otherwise. In this case, return x^y; is sufficient and, if the test program complains, it is improperly written.The difference between x^y and !(!(x^y)) is that when x and y are unequal, the former might take a wide range of nonzero values, but the latter will evaluate to exactly 1.
Any non-zero value is truthy in C, so your simpler implementation is plausible. It does not match the behavior of the != operator, however, which always evaluates to either 0 or 1, not any other value. Presumably, then, the latter behavior is what was expected. If the exercise was not clear about that then it was flawed, and you might have a case for a re-grade.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With