VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-two-numbers-are-equal-without-using-arithmetic-and-comparison-operators/

⇱ Check if two numbers are equal without using arithmetic and comparison operators - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if two numbers are equal without using arithmetic and comparison operators

Last Updated : 23 Jul, 2025

Given two numbers, the task is to check if two numbers are equal without using Arithmetic and Comparison Operators or String functions.

Method 1 : The idea is to use XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. 


Output
Not Same

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 2 : Here idea is using complement ( ~ ) and bit-wise '&' operator. 


Output
Not Same

Time Complexity: O(1)
Auxiliary Space: O(1)

Using bit manipulation:

Approach:

Another approach is to use bit manipulation to compare each bit of the two numbers. We can use the bit-shift operators to extract each bit and compare them one by one.

  • Define a function named is_equal that takes two arguments num1 and num2.
  • Initialize a variable mask to 1.
  • Loop through the range of 32 bits (assuming 32-bit integers).
  • Use the bitwise AND operator (&) to extract the i-th bit of num1 and num2.
  • Compare the extracted bits using the not equal to operator (!=).
  • If the extracted bits are not equal, return False.
  • Shift the mask left by one bit using the left shift operator (<<).
  • Return True if all bits are equal.

Output
True
False

Time complexity: O(log n)
Space complexity: O(1)


Source: https://www.geeksforgeeks.org/dsa/count-of-n-digit-numbers-whose-sum-of-digits-equals-to-given-sum/

Comment
Article Tags:
Article Tags: