Friday, 19 August 2016

Anirudh

Check if two integers are equal without using any comparison operators

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.
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
}

Anirudh

About the author →

Anirudh Khanna is a Computer Science student and a geek who firmly believes in the awesomeness of technology! He is a programmer and web designer, also keenly interested in the research of new and innovative ideas in Computer Science.

Subscribe to Geek Factorial via email :