Python program to check if binary representation of two numbers are anagram.



The binary numbers are the basis of how data is stored, processed and transferred. Every integer is internally represented by using a sequence of bits (combination of 0s and 1s).

In this article, we will learn how to check if binary representation of two numbers are anagram. Two numbers are said to be binary anagrams if their binary representations contains the same number of 1s and 0s. For example, the number 12 in binary is 1100 and the number 10 in binary is 1010, both have two 0s and two 1s, making them binary anagrams.

Using collections.Counter() Class

The collections module in python provides the specialized container datatypes, Counter is one among them.

Counter is a subclass of the dictionary that is designed to count the hashable objects. It takes an iterable or mapping and returns the dictionary-like object, Where elements are stored as keys and their counts as values.

Syntax

Following is the syntax of collections.Counter() class-

from collections import Counter
Counter(iterable)

Example 1

Let's look at the following example, where we are going to take the numbers 12 and 10 for checking whether they are binary anagrams or not.

from collections import Counter
def demo(a, b):
    x1 = bin(a)[2:]
    x2 = bin(b)[2:]
    print(f"Binary of {a} : {x1}")
    print(f"Binary of {b} : {x2}")
    return Counter(x1) == Counter(x2)
a = 12
b = 10
result = demo(a, b)
print("Result :", result)

The output of the above program is as follows -

Binary of 12 : 1100
Binary of 10 : 1010
Result : True

Example 2

Consider the another scenario, where we are going to check whether the 10 and 6 are the binary anagrams.

from collections import Counter
def demo(a, b):
    x1 = bin(a)[2:]
    x2 = bin(b)[2:]
    print(f"Binary of {a} : {x1}")
    print(f"Binary of {b} : {x2}")
    return Counter(x1) == Counter(x2)
a = 10
b = 6
result = demo(a, b)
print("Output:", result)

The output of the above program is as follows -

Binary of 10 : 1010
Binary of 6 : 110
Output: False
Updated on: 2025-08-28T13:42:15+05:30

754 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements