Open In App

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

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

C++




// C++ program to check if two numbers
// are equal without using arithmetic
// and comparison operators
#include <iostream>
using namespace std;
 
// Function to check if two
// numbers are equal using
// XOR operator
void areSame(int a, int b)
{
    if (a ^ b)
        cout << "Not Same";
    else
        cout << "Same";
}
 
// Driver Code
int main()
{
 
    // Calling function
    areSame(10, 20);
}


Java




// Java program to check if two numbers
// are equal without using arithmetic
// and comparison operators
class GFG {
 
    // Function to check if two
    // numbers are equal using
    // XOR operator
    static void areSame(int a, int b)
    {
        if ((a ^ b) != 0)
            System.out.print("Not Same");
        else
            System.out.print("Same");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Calling function
        areSame(10, 20);
    }
}
 
// This code is contributed by Smitha


Python3




# Python3 program to check if two numbers
# are equal without using arithmetic
# and comparison operators
 
def areSame(a, b):
 
# Function to check if two
# numbers are equal using
# XOR operator
 if ((a ^ b) != 0):
    print("Not Same")
 else:
    print("Same")
 
# Driver Code
 
areSame(10, 20)
 
# This code is contributed by Smitha


C#




// C# program to check if two numbers
// are equal without using arithmetic
// and comparison operators
using System;
 
class GFG {
 
    // Function to check if two
    // numbers are equal using
    // XOR operator
    static void areSame(int a, int b)
    {
        if ((a ^ b) != 0)
            Console.Write("Not Same");
        else
            Console.Write("Same");
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        // Calling function
        areSame(10, 20);
    }
}
 
// This code is contributed by Smitha


Javascript




<script>
 
// Javascript program to check if two numbers
// are equal without using arithmetic and
// comparison operators  
 
// Function to check if two
// numbers are equal using
// XOR operator
function areSame(a, b)
{
    if ((a ^ b) != 0)
        document.write("Not Same");
    else
        document.write("Same");
}
 
// Driver Code
areSame(10, 20);
 
// This code is contributed by shikhasingrajput
 
</script>


PHP




<?php
// PHP program to check if
// two numbers are equal
// without using arithmetic
// and comparison operators
 
// Function to check if two
// numbers are equal using
// XOR operator
function areSame($a, $b)
{
if ($a ^ $b)
echo "Not Same";
else
echo "Same";
}
 
// Driver Code
 
// Calling function
areSame(10, 20);
 
// This code is contributed
// by nitin mittal.
?>


Output

Not Same




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

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

C++




// C++ program to check if two numbers
// are equal without using arithmetic
// and comparison operators
#include <iostream>
using namespace std;
 
// Function to check if two
// numbers are equal using
// using ~ complement and & operator.
void areSame(int a, int b)
{
    if ((a & ~b) == 0)
        cout << "Same";
    else
        cout << "Not Same";
}
// Driver Code
int main()
{
 
    // Calling function
    areSame(10, 20);
   
  // This Code is improved by Sonu Kumar Pandit
}


Java




// Java program to check if two numbers
// are equal without using arithmetic
// and comparison operators
 
class GFG {
    // Function to check if two
    // numbers are equal using
    // using ~ complement and & operator.
    static void areSame(int a, int b)
    {
        if ((a & ~b) == 0 && (~a & b) == 0)
            System.out.print("Same");
        else
            System.out.print("Not Same");
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Calling function
        areSame(10, 20);
    }
}
 
// This code is contributed
// by Akanksha Rai


Python3




# Python3 program to check if two numbers
# are equal without using arithmetic
# and comparison operators
 
# Function to check if two
# numbers are equal using
# using ~ complement and & operator.
 
 
def areSame(a, b):
    if ((a & ~b) == 0 and (~a & b) == 0):
        print("Same")
    else:
        print("Not Same")
 
 
# Calling function
areSame(10, 20)
 
# This code is contributed by Rajput-Ji


C#




// C# program to check if two numbers
// are equal without using arithmetic
// and comparison operators
using System;
 
class GFG {
    // Function to check if two
    // numbers are equal using
    // using ~ complement and & operator.
    static void areSame(int a, int b)
    {
        if ((a & ~b) == 0 && (~a & b) == 0)
            Console.Write("Same");
        else
            Console.Write("Not Same");
    }
 
    // Driver Code
    public static void Main()
    {
        // Calling function
        areSame(10, 20);
    }
}
 
// This code is contributed
// by Akanksha Rai


Javascript




<script>
 
// Javascript program to check if two numbers
// are equal without using arithmetic
// and comparison operators
 
// Function to check if two
// Numbers are equal using
// using ~ complement and & operator.
function areSame(a, b)
{
    if ((a & ~b) == 0 && (~a & b) == 0)
        document.write("Same");
    else
        document.write("Not Same");
}
 
// Driver Code
 
// Calling function
areSame(10, 20);
 
// This code is contributed by gauravrajput1
 
</script>


PHP




<?php
// PHP program to check if two numbers
// are equal without using arithmetic
// and comparison operators
 
// Function to check if two
// numbers are equal using
// using ~ complement and & operator.
function areSame($a, $b)
{
    if (($a & ~$b)==0 && (~$a & $b)==0)
        echo "Same";
    else
        echo "Not Same";
}
 
// Driver Code
// Calling function
areSame(10, 20);
 
// This code is contributed by ita_c
?>


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.

C++




// CPP code for the above approach
#include <iostream>
using namespace std;
 
bool isEqual(int num1, int num2)
{
    int mask = 1;
    for (int i = 0; i < 32;
         i++) { // assuming 32-bit integers
        if ((num1 & mask) != (num2 & mask)) {
            return false;
        }
        mask <<= 1;
    }
    return true;
}
 
int main()
{
    // Example usage
    cout << (isEqual(10, 10) ? "True" : "False") << endl; // Output: 1 (true)
    cout << (isEqual(10, 20) ? "True" : "False") << endl; // Output: 0 (false)
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Java




// Java code for the above approach
 
public class GFG {
    // Function to check if two numbers have equal binary
    // representation
    static boolean isEqual(int num1, int num2)
    {
        int mask = 1;
        for (int i = 0; i < 32;
             i++) { // assuming 32-bit integers
            if ((num1 & mask) != (num2 & mask)) {
                return false;
            }
            mask <<= 1;
        }
        return true;
    }
 
    // Main method to demonstrate the usage
    public static void main(String[] args)
    {
        // Example usage
        System.out.println(isEqual(10, 10)
                               ? "True"
                               : "False"); // Output: true
        System.out.println(isEqual(10, 20)
                               ? "True"
                               : "False"); // Output: false
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




def is_equal(num1, num2):
    mask = 1
    for i in range(32):  # assuming 32-bit integers
        if (num1 & mask) != (num2 & mask):
            return False
        mask <<= 1
    return True
 
# Example usage
print(is_equal(10, 10))  # Output: True
print(is_equal(10, 20))  # Output: False


C#




using System;
 
class Program
{
    static bool IsEqual(int num1, int num2)
    {
        int mask = 1;
 
        for (int i = 0; i < 32; i++) // assuming 32-bit integers
        {
            // If the bits at the current position are different, return false
            if ((num1 & mask) != (num2 & mask))
            {
                return false;
            }
 
            mask <<= 1;
        }
 
        // All corresponding bits are equal, return true
        return true;
    }
 
    static void Main()
    {
        // Example usage
        Console.WriteLine(IsEqual(10, 10) ? "True" : "False"); // Output: True
        Console.WriteLine(IsEqual(10, 20) ? "True" : "False"); // Output: False
    }
}
// This code is contributed by shivamgupta310570


Javascript




// Function to check if two numbers have equal binary representation
function isEqual(num1, num2) {
    let mask = 1;
    for (let i = 0; i < 32; i++) { // assuming 32-bit integers
        if ((num1 & mask) !== (num2 & mask)) {
            return false;
        }
        mask <<= 1;
    }
    return true;
}
 
// Main method to demonstrate the usage
console.log(isEqual(10, 10) ? "True" : "False"); // Output: true
console.log(isEqual(10, 20) ? "True" : "False"); // Output: false


Output

True
False




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

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



Previous Article
Next Article

Similar Reads

Check if two numbers are equal without using comparison operators
The following are not allowed to use Comparison Operators String function Examples: Input : num1 = 1233, num2 =1233Output : Same Input : num1 = 223, num2 = 233Output : Not Same Method 1: The idea is to use the XOR operator. XOR of two numbers is 0 if the numbers are the same, otherwise non-zero. C/C++ Code #include &lt;iostream&gt; using namespace
5 min read
Add two numbers without using arithmetic operators
Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, --, -, .. etc). Method 1: C/C++ Code #include &lt;iostream&gt; using namespace std; int add(int a, int b) { // for loop will start from 1 and move till the value of // second number , first number(a) is incremented in for //
9 min read
Subtract two numbers without using arithmetic operators
Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use subtractor logic. The truth table for the half sub
8 min read
How to sum two integers without using arithmetic operators in C/C++?
Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) { char *p = a; return (int)&amp;amp;p[b]; } Despite
4 min read
Check if n is divisible by power of 2 without using arithmetic operators
Given two positive integers n and m. The problem is to check whether n is divisible by 2m or not without using arithmetic operators. Examples: Input : n = 8, m = 2 Output : Yes Input : n = 14, m = 3 Output : No Approach: If a number is divisible by 2 then it has its least significant bit (LSB) set to 0, if divisible by 4 then two LSB's set to 0, if
4 min read
Smallest of three integers without comparison operators
Write a program to find the smallest of three integers, without using any of the comparison operators. Let 3 input numbers be x, y and z.Method 1 (Repeated Subtraction) Take a counter variable c and initialize it with 0. In a loop, repeatedly subtract x, y and z by 1 and increment c. The number which becomes 0 first is the smallest. After the loop
10 min read
Smallest perfect power of 2 greater than n (without using arithmetic operators)
Given a non-negative integer n. The problem is to find the smallest perfect power of 2 which is greater than n without using the arithmetic operators.Examples : Input : n = 10 Output : 16 Input : n = 128 Output : 256 Algorithm : C/C++ Code // C++ implementation of smallest perfect power // of 2 greater than n #include &lt;bits/stdc++.h&gt; using na
4 min read
Decimal to binary conversion without using arithmetic operators
Find the binary equivalent of the given non-negative number n without using arithmetic operators. Examples: Input : n = 10Output : 1010 Input : n = 38Output : 100110 Note that + in below algorithm/program is used for concatenation purpose. Algorithm: decToBin(n) if n == 0 return "0" Declare bin = "" Declare ch while n &gt; 0 if (n &amp; 1) == 0 ch
8 min read
Subtract 1 without arithmetic operators
Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed. Examples: Input: 12Output: 11 Input: 6Output: 5 Method 1 To subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we get 0011001111). Finally, flip the rightmost 1 bit also (we get 00
6 min read
Compare two integers without using any Comparison operator
Given two integers A &amp; B. Task is to check if A and B are same or not without using comparison operators.Examples: Input : A = 5 , B = 6Output : 0 Input : A = 5 , B = 5 Output : 1 Note : 1 = "YES" and 0 = "NO" The idea is pretty simple we do Xor of both elements ( A, B ). if Xor is zero then two numbers are equal else not. Below is the implemen
5 min read
Article Tags :
Practice Tags :