Last Updated : 30 Jun, 2023
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.
Examples:
Input : a = 8, b = 4
Output : Yes
Binary representations of both
numbers have same 0s and 1s.
Input : a = 4, b = 5
Output : No
We have existing solution for this problem please refer Check if binary representations of two numbers are anagram link. We can solve this problem quickly in python using Counter(iterable) method and Dictionary Comparison. Approach is simple,
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1,num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin(num1)[2:]
bin2 = bin(num2)[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 representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 == dict2:
print('Yes')
else:
print('No')
# Driver program
if __name__ == "__main__":
num1 = 8
num2 = 4
checkAnagram(num1,num2)
Output:
YesCheck if binary representations of two numbers are Using zfill
This approach checks if the binary representations of two given numbers are anagrams or not. It first converts the numbers to their binary form and pads zeros to make it of length 32. It then counts the occurrences of 0s and 1s in each binary representation using two separate counters. Finally, it compares the counts of 0s and 1s for both numbers and returns "Yes" if they are equal, otherwise "No".
Algorithm1. Convert both input integers into their binary representation using bin() function.
2. Fill each binary string with zeros to the left, so that they all have length of 32 bits, using zfill() method.
3. For each binary string, count the frequency of 0s and 1s and store them in count_a and count_b lists.
4. Check if the two lists are equal.
5. If the two lists are equal, return "Yes", else return "No".
def is_anagram_binary(a, b):
bin_a = bin(a)[2:].zfill(32)
bin_b = bin(b)[2:].zfill(32)
count_a = [0, 0]
count_b = [0, 0]
for i in range(32):
if bin_a[i] == '0':
count_a[0] += 1
else:
count_a[1] += 1
if bin_b[i] == '0':
count_b[0] += 1
else:
count_b[1] += 1
if count_a == count_b:
return "Yes"
else:
return "No"
a = 8
b = 4
print( is_anagram_binary(8, 4)) # Output: True
Time complexity of this code is O(1) since the length of the binary representation is constant.
Auxiliary Space is also O(1) since the count lists are of constant size.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4