Determine if two integers are equal without using comparison and arithmetic operators

In this post, we will discuss how to determine if two integers are equal without using comparison operators (==, !=, <, >, <=, >=) & arithmetic operators (+, -, *, /, %).

 

1. Using Bitwise XOR operator

The simplest solution is to use Bitwise XOR operator. We know that for equal numbers, the XOR operator returns 0. We can make use of this fact as shown below:

 

Download   Run Code

Output:

x=10 is equal to y=10

 

2. Using Array Index + Ternary Operator

We can also take advantage of the fact that by default a garbage value is assigned to a local array in C. The idea is to use first number as array index and set the value to 0. Then we simply check if array is set for second number or not.

Please note that this solution won’t work on negative numbers, consumes a lot of memory, and might try to access invalid indices of the array.

 

Download   Run Code

Output:

x=10 is equal to y=10

 

3. Hashing:

Since previous approach consumes a lot of memory, a more space efficient version is to use std::unordered_map in C++. Below is C++ implementation:

 

Download   Run Code

Output:

x is not equal to y

 
We can also use std::unordered_set where we insert the first number in the set and then simply check if second number exists in the set or not.

 

4. Repeated Subtraction:

The idea here is to repeatedly subtract both numbers (say x and y) parallely until one of the numbers becomes 0. If the numbers are equal, then we should be left with x = 0 and y = 1. The solution uses decrement operator (a unary operator) for repeated subtraction.

 

Download   Run Code

Output:

x=5 is not equal to y=8

 

5. Simple substraction

If we’re permitted to use arithmetic operators, we can perform simple subtraction to determine if two integers are equal as shown below:

 

Download   Run Code

Output:

x=10 is equal to y=10

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz