
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Binary Representations of Two Numbers Are Anagram in Java
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
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");
Advertisements