Signup/Sign In

Check if binary representations of two numbers are an anagram

In this tutorial, you will learn to write a Python Program where we can check if the binary representation of two numbers is an anagram. A number is said to be an anagram if both the numbers have the same characters in a different order. Suppose we have two numbers say 9 and 12 then we have to check if the binary representation of these two numbers is an anagram or not. The binary representation of 9 is 1001 and the binary representation of 12 is 1100, so these two are anagrams of each other. Hence, our program should display Yes as output.

Look at the sample input-output format.

Input:

a= 13

b= 3

Output: No

Input:

a= 12

b= 9

Output: Yes

The approach to solving this problem is to first convert integer numbers to binary numbers using the bin() method. Since the length of the binary representation can have different lengths then we will append 0s to make the length equal. We will convert each of the binary strings to a dictionary using Counter() function. Then we will check if the 0s and 1s in both the dictionary are equal, if they are equal then they are anagram else they are not.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Import Counter from collections

Step 2- Define a function to check if two binary numbers are anagrams, it will accept two integers as parameters

Step 3- Convert integer numbers to binary numbers using bin()

Step 4- Append zeroes to make the length of binary numbers equal

Step 5- Convert binary string to dictionary

Step 6- Compare if both dictionaries are equal

Step 7- Print yes if they are equal

Step 8- Print no if they are not equal

Step 9- Declare two numbers and pass them in the function

Python Program

Look at the Python code to understand the implementation. After converting to binary, we have used slicing to remove the first two characters from the string returned by the bin() method. It returns a string with the prefix '0b', which will be removed using slicing.

from collections import Counter
  
def checkAnagram(n1,n2):
  
    # convert numbers into binary
    bin1 = bin(n1)[2:]
    bin2 = bin(n2)[2:]
  
    # append zeros in shorter string
    zeros = abs(len(bin1)-len(bin2))
    if (len(bin1)>len(bin2)):
         bin2 = zeros * '0' + bin2
    else:
         bin1 = zeros * '0' + bin1
  
    # convert binary to  dictionary
    dict1 = Counter(bin1)
    dict2 = Counter(bin2)
  
    # compare both dictionaries
    if dict1 == dict2:
         print('Yes')
    else:
         print('No')
  
n1 = 11
n2 = 3
checkAnagram(n1,n2)


No

Conclusion

In this tutorial, we have seen how to convert integer to binary and check if the binary representation is an anagram or not. We have used a dictionary to compare characters in the string and check if they are anagrams.