Problem statement: Given two integers, you need to check if they are equal or not, without using any comparison operators.
Solution: An optimized solution can be given using bitwise XOR operator. The bitwise XOR of two numbers is 0 only if each corresponding bit in the two numbers is same, i.e. the numbers are equal.
Since (a ^ b) might be any integer value, we can strictly restrict the return value to either 0 or 1 like this:
Another simple solution could be using the minus operator:
Solution: An optimized solution can be given using bitwise XOR operator. The bitwise XOR of two numbers is 0 only if each corresponding bit in the two numbers is same, i.e. the numbers are equal.
int isUnequal(int a, int b) { return a ^ b; // Returns zero if the numbers are equal, else a non-zero value }
Since (a ^ b) might be any integer value, we can strictly restrict the return value to either 0 or 1 like this:
int isUnequal(int a, int b) { return !!(a ^ b); // Returns zero if the numbers are equal, else returns one }
Another simple solution could be using the minus operator:
int isUnequal(int a, int b) { return !!(a - b); // Returns zero if the numbers are equal, else returns one }