Check if binary representation of a given number and its complement are anagram
Last Updated :
30 Mar, 2023
Given a positive number you need to check whether it's complement and the number are anagrams or not.
Examples:
Input : a = 4294967295
Output : Yes
Binary representation of 'a' and it's
complement are anagrams of each other
Input : a = 4
Output : No
Simple Approach: In this approach calculation of the complement of the number is allowed.
1. Find binary representation of the number and it's complement using simple decimal to binary representation technique.
2. Sort both the binary representations and compare them to check whether they are anagrams or not.
CPP
// A simple C++ program to check if binary
// representations of a number and it's
// complement are anagram.
#include <bits/stdc++.h>
#define ull unsigned long long int
using namespace std;
const int ULL_SIZE = 8 * sizeof(ull);
bool isComplementAnagram(ull a)
{
ull b = ~a; // Finding complement of a;
// Find reverse binary representation of a.
bool binary_a[ULL_SIZE] = { 0 };
for (int i = 0; a > 0; i++) {
binary_a[i] = a % 2;
a /= 2;
}
// Find reverse binary representation
// of complement.
bool binary_b[ULL_SIZE] = { 0 };
for (int i = 0; b > 0; i++) {
binary_b[i] = b % 2;
b /= 2;
}
// Sort binary representations and compare
// after sorting.
sort(binary_a, binary_a + ULL_SIZE);
sort(binary_b, binary_b + ULL_SIZE);
for (int i = 0; i < ULL_SIZE; i++)
if (binary_a[i] != binary_b[i])
return false;
return true;
}
// Driver code
int main()
{
ull a = 4294967295;
cout << isComplementAnagram(a) << endl;
return 0;
}
Java
// A simple JAVA program to check if binary
// representations of a number and it's
// complement are anagram.
import java.math.BigInteger;
import java.util.*;
class GFG {
// Method to discard the signed bit of the byte array
// inorder to convert the numbers to unsigned
static byte[] toUnsigned(byte[] byteArray)
{
BigInteger b = new BigInteger(byteArray);
b = b.ONE.shiftLeft(128);
return b.toByteArray();
}
// Method to check if a number and its complement
// are anagrams
static int isComplementAnagram(BigInteger a)
{
// converting a to an unsigned byte array
byte[] binary_a = a.toByteArray();
binary_a = toUnsigned(binary_a);
// constructing byte array of complement of a
byte[] binary_b = new byte[binary_a.length];
// inverting the bits of a
for (int i = 0; i < binary_a.length; i++) {
binary_b[i] = (byte)(binary_a[i] ^ 0xFF);
}
binary_b = toUnsigned(binary_b);
// Sort binary representations
Arrays.sort(binary_a);
Arrays.sort(binary_b);
// converting a and ~a to unsigned after sorting
binary_a = toUnsigned(binary_b);
binary_b = toUnsigned(binary_b);
// comparing the binary representations
for (int i = 0; i < binary_a.length; i++)
if (binary_a[i] != binary_b[i])
return 0;
return 1;
}
// Driver code
public static void main(String[] args)
{
BigInteger a = new BigInteger("4294967295");
// Function call
System.out.println(isComplementAnagram(a));
}
}
// This code is contributed by phasing17
Python3
# Python3 program to check if binary
# representations of a number and it's
# complement are anagram.
ULL_SIZE = 8 * 8
def isComplementAnagram(a):
# Find reverse binary representation of a.
binary_a = [0 for _ in range(ULL_SIZE)]
binary_b = [0 for _ in range(ULL_SIZE)]
i = 0
while a > 0:
binary_a[i] = a % 2
a = int(a / 2)
i += 1
# Find reverse binary representation
# of complement.
for i in range(ULL_SIZE):
binary_b[i] = 1 - binary_a[i]
# Sort binary representations and compare
# after sorting.
binary_a.sort()
binary_b.sort()
for i in range(ULL_SIZE):
if (binary_a[i] != binary_b[i]):
return 0
return 1
# Driver code
a = 4294967295
print(isComplementAnagram(a))
# This code is contributed by phasing17
JavaScript
// JS program to check if binary
// representations of a number and it's
// complement are anagram.
const ULL_SIZE = 8 * 8;
function isComplementAnagram(a)
{
// Find reverse binary representation of a.
var binary_a = new Array(ULL_SIZE).fill(0);
var binary_b = new Array(ULL_SIZE).fill(0);
for (var i = 0; a > 0; i++)
{
binary_a[i] = a % 2;
a = Math.floor(a / 2);
}
// Find reverse binary representation
// of complement.
for (var i = 0; i < ULL_SIZE; i++)
{
binary_b[i] = 1 - binary_a[i];
}
// Sort binary representations and compare
// after sorting.
binary_a.sort();
binary_b.sort();
for (var i = 0; i < ULL_SIZE; i++)
if (binary_a[i] != binary_b[i])
return false;
return true;
}
// Driver code
var a = 4294967295;
console.log(isComplementAnagram(a));
//This code is contributed by phasing17
C#
// C# program to check if binary representations of a
// number and it's complement are anagram.
using System;
using System.Linq;
public class GFG {
const int ULL_SIZE = 8 * 8;
static bool IsComplementAnagram(ulong a)
{
// Find reverse binary representation of a.
var binary_a = new int[ULL_SIZE];
var binary_b = new int[ULL_SIZE];
for (int i = 0; a > 0; i++) {
binary_a[i] = (int)(a % 2);
a = (ulong)Math.Floor((double)a / 2);
}
// Find reverse binary representation of complement.
for (int i = 0; i < ULL_SIZE; i++) {
binary_b[i] = 1 - binary_a[i];
}
// Sort binary representations and compare after
// sorting.
Array.Sort(binary_a);
Array.Sort(binary_b);
for (int i = 0; i < ULL_SIZE; i++) {
if (binary_a[i] != binary_b[i]) {
return false;
}
}
return true;
}
static public void Main()
{
// Code
ulong a = 4294967295;
Console.WriteLine(IsComplementAnagram(a) ? 1 : 0);
}
}
// This code is contributed by karthik.
Output:
1
Time Complexity : O(logn*log(logn)) where n is the given number.
Auxiliary Space: O(ULL_SIZE) where ULL_SIZE is defined constant.
Efficient Approach: Just count the number of 1's present in the bit representation of the given number. If number of 1's present are 32 then it's complement will also have 32 1's in it's bit representation and they will be anagrams of each other.
C++
// An efficient C++ program to check if binary
// representations of a number and it's complement are anagram.
#include <bits/stdc++.h>
#define ull unsigned long long int
using namespace std;
const int ULL_SIZE = 8*sizeof(ull);
// Returns true if binary representations of
// a and b are anagram.
bool bit_anagram_check(ull a)
{
// _popcnt64(a) gives number of 1's present
// in binary representation of a. If number
// of 1s is half of total bits, return true.
return (_popcnt64(a) == (ULL_SIZE >> 1));
}
int main()
{
ull a = 4294967295;
cout << bit_anagram_check(a) << endl;
return 0;
}
Java
// An efficient Java program to check if binary
// representations of a number and it's complement are anagram.
class GFG
{
static byte longSize = 8;
static int ULL_SIZE = 8*longSize;
// Returns true if binary representations of
// a and b are anagram.
static boolean bit_anagram_check(long a)
{
// _popcnt64(a) gives number of 1's present
// in binary representation of a. If number
// of 1s is half of total bits, return true.
return (Integer.bitCount((int)a) == (ULL_SIZE >> 1));
}
// Driver code
public static void main(String[] args)
{
long a = 4294967295L;
System.out.println(bit_anagram_check(a));
}
}
/* This code contributed by PrinciRaj1992 */
Python3
# An efficient Python3 program to check
# if binary representations of a number
# and it's complement are anagram.
ULL_SIZE = 64
# Returns true if binary representations of
# a and b are anagram.
def bit_anagram_check(a):
#_popcnt64(a) gives number of 1's present
# in binary representation of a. If number
# of 1s is half of total bits, return true.
return (bin(a).count("1") == (ULL_SIZE >> 1))
# Driver Code
a = 4294967295
print(int(bit_anagram_check(a)))
# This code is contributed by Mohit Kumar
C#
// An efficient C# program to check
// if binary representations of
// a number and it's complement
// are anagram.
using System;
class GFG
{
static byte longSize = 8;
static int ULL_SIZE = 8*longSize;
// Returns true if binary representations of
// a and b are anagram.
static bool bit_anagram_check(long a)
{
// _popcnt64(a) gives number of 1's present
// in binary representation of a. If number
// of 1s is half of total bits, return true.
return (BitCount((int)a) == (ULL_SIZE >> 1));
}
static int BitCount(int n)
{
int count = 0;
while (n != 0)
{
count++;
n &= (n - 1);
}
return count;
}
// Driver code
public static void Main(String[] args)
{
long a = 4294967295L;
Console.WriteLine(bit_anagram_check(a));
}
}
// This code has been contributed by 29AjayKumar
PHP
<?php
// An efficient PHP program to check
// if binary representations of
// a number and it's complement
// are anagram.
// Returns true if binary representations
// of a and b are anagram.
function bit_anagram_check($a)
{
$longSize = 8;
$ULL_SIZE = 8 * $longSize;
// _popcnt64(a) gives number of 1's present
// in binary representation of a. If number
// of 1s is half of total bits, return true.
return (BitCount($a) == ($ULL_SIZE >> 1));
}
function BitCount($n)
{
$count = 0;
while ($n != 0)
{
$count++;
$n &= ($n - 1);
}
return $count;
}
// Driver code
$a = 4294967295;
echo(bit_anagram_check($a));
// This code contributed by Rajput-Ji
?>
JavaScript
<script>
// An efficient javascript
// program to check if binary
// representations of a number and
// it's complement are anagram.
var longSize = 8;
var ULL_SIZE = 8*longSize;
// Returns true if binary representations of
// a and b are anagram.
function bit_anagram_check(a)
{
// _popcnt64(a) gives number of 1's present
// in binary representation of a. If number
// of 1s is half of total bits, return true.
var ans =a.toString(2).split('0').join('').length
== (ULL_SIZE >> 1)?1:0;
return ans;
}
// Driver code
var a = 4294967295;
document.write(bit_anagram_check(a));
// This code contributed by shikhasingrajput
</script>
Output:
1
Time Complexity : O(1)
Auxiliary Space: O(1)
Note:
1. The answer is only dependent on the number, in the above approach we don't even find the need to obtain the complement of the number.
2. The above code uses GCC specific functions. If we wish to write code for other compilers, we may use Count set bits in an integer.
Similar Reads
Check if binary representations of two numbers are anagram 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 Simple Approach: Find the Binary Representation
9 min read
Check if given number contains only â01â and â10â as substring in its binary representation Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substrin
6 min read
Python Dictionary | Check if binary representations of two numbers are anagram 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 : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe ha
3 min read
Check if actual binary representation of a number is palindrome Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0âs are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
6 min read
Check if binary representation of a number is palindrome Given an integer x, determine whether its binary representation is a palindrome. Return true if it is a palindrome; otherwise, return false.Input: x = 9Output: trueExplanation: The binary representation of 9 is 1001, which is a palindrome.Input: x = 10Output: falseExplanation: The binary representat
9 min read
Binary representation of a given number Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length.Examples: Input: n = 2Output: 00000000000000000000000000000010Input: n = 0Output: 000000000000
6 min read
Check if a given number can be represented in given a no. of digits in any base Given a number and no. of digits to represent the number, find if the given number can be represented in given no. of digits in any base from 2 to 32.Examples : Input: 8 4 Output: Yes Possible in base 2 as 8 in base 2 is 1000 Input: 8 2 Output: Yes Possible in base 3 as 8 in base 3 is 22 Input: 8 3
12 min read
Check in binary array the number represented by a subarray is odd or even Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even Examples : Input : arr = {1, 1, 0, 1} l = 1, r = 3 Output : odd number represented by arr[l...r] is 101 which 5 in decimal form which is odd Input : arr = {1, 1, 1, 1}
4 min read
Check if the binary representation of a number has equal number of 0s and 1s in blocks Given an integer N, the task is to check if its equivalent binary number has an equal frequency of consecutive blocks of 0 and 1. Note that 0 and a number with all 1s are not considered to have a number of blocks of 0s and 1s. Examples: Input: N = 5 Output: Yes Equivalent binary number of 5 is 101.
10 min read
Check if binary representations of 0 to N are present as substrings in given binary string Give binary string str and an integer N, the task is to check if the substrings of the string contain all binary representations of non-negative integers less than or equal to the given integer N. Examples: Input: str = â0110", N = 3 Output: True Explanation: Since substrings â0", â1", â10", and â11
9 min read