# Java program to check if binary representations of two numbers are anagram

Java 8Object Oriented ProgrammingProgramming

The binary representations of two numbers are anagrams if they have the same number of 0’a and 1’s. An example of this is given as follows −

Number 1 = 3
Binary representation of Number 1 = 0011
Number 2 = 12
Binary representation of Number 2 = 1100

The two numbers are anagram.

A program that demonstrates this is given as follows −

## Example

Live Demo

public class Example {
public static void main (String[] args) {
long x = 12, y = 3;
if(Long.bitCount(x) == Long.bitCount(y))
System.out.println("Binary representations of " + x + " and " + y + " are anagrams");
else
System.out.println("Binary representations of " + x + " and " + y + " are not anagrams");
}
}

The output of the above program is as follows −

Binary representations of 12 and 3 are anagrams

Now let us understand the above program.

The values of x and y are defined. Then the 1’s in the bit representation are counted. If they are equal, then the binary representations of x and y are anagrams otherwise not. The code snippet that demonstrates this is given as follows −

long x = 12, y = 3;
if(Long.bitCount(x) == Long.bitCount(y))
System.out.println("Binary representations of " + x + " and " + y + " are anagrams");
else
System.out.println("Binary representations of " + x + " and " + y + " are not anagrams");
Published on 26-Dec-2018 12:09:35
Advertisements