This post will discuss how to determine whether two integers are equal without using comparison operators (==, !=, <, >, <=, >=) and arithmetic operators (+, -, *, /, %).

1. Using Bitwise XOR Operator

The simplest solution is to use the bitwise XOR operator. We know that for equal numbers, the XOR operator returns 0. We can make use of this fact, demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

x=10 is equal to y=10

Java


Download  Run Code

Output:

x=10 is equal to y=10

Python


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 a garbage value is assigned to a local array in C by default. The idea is to use the first number as the array index and set the value to 0. Then, check if the array is set for the second number or not.

Following is the C, Java, and Python implementation of the idea. Please note that this solution won’t work on negative numbers, consumes a lot of memory, and might access the array’s invalid indices.

C


Download  Run Code

Output:

x=10 is equal to y=10

Java


Download  Run Code

Output:

x=10 is equal to y=10

3. Using Hashing

Since the previous approach consumes a lot of memory, a more space-efficient version uses a hash map. The hash-based implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

x is not equal to y

Java


Download  Run Code

Output:

x is not equal to y

Python


Download  Run Code

Output:

x is not equal to y

We can also use a hash set where we insert the first number into the set and then check if the second number exists in the set or not.

4. Repeated Subtraction

Here, the idea is to repeatedly subtract both numbers, say x and y, parallelly until one of the numbers becomes 0. If the numbers are equal, we should be left with x = 0 and y = 1.

Following is the C, Java, and Python program that demonstrates it. The solution uses the decrement operator (a unary operator) for repeated subtraction.

C


Download  Run Code

Output:

x=5 is not equal to y=8

Java


Download  Run Code

Output:

x=5 is not equal to y=8

5. Simple Subtraction

If we are permitted to use arithmetic operators, perform a simple subtraction to determine whether two integers are equal, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

x=10 is equal to y=10

Java


Download  Run Code

Output:

x=10 is equal to y=10

Python


Download  Run Code

Output:

x=10 is equal to y=10