Check if B can be formed by permuting the binary digits of A
Last Updated :
20 Dec, 2022
Given two integer A and B, the task is to check whether the binary representation of B can be generated by permuting the binary digits of A.
Examples:
Input: A = 3, B = 9
Output: Yes
Binary(3) = 0011 and Binary(9) = 1001
Input: A = 6, B = 7
Output: No
Approach: The idea is to count the number of set bits in the binary representations of both the numbers, now if they are equal then the answer is Yes or else the answer is No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossible( int a, int b)
{
int cntA = __builtin_popcount(a);
int cntB = __builtin_popcount(b);
if (cntA == cntB)
return true ;
return false ;
}
int main()
{
int a = 3, b = 9;
if (isPossible(a, b))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
public class GFG
{
public static int countSetBits( int n)
{
if (n == 0 )
return 0 ;
else
return (n & 1 ) + countSetBits(n >> 1 );
}
static boolean isPossible( int a, int b)
{
int cntA = countSetBits(a);
int cntB = countSetBits(b);
if (cntA == cntB)
return true ;
return false ;
}
public static void main (String[] args)
{
int a = 3 , b = 9 ;
if (isPossible(a, b))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def bitsoncount(x):
return bin (x).count( '1' )
def isPossible(a, b):
cntA = bitsoncount(a);
cntB = bitsoncount(b);
if (cntA = = cntB):
return True
return False
a = 3
b = 9
if (isPossible(a, b)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public static int countSetBits( int n)
{
if (n == 0)
return 0;
else
return (n & 1) + countSetBits(n >> 1);
}
static bool isPossible( int a, int b)
{
int cntA = countSetBits(a);
int cntB = countSetBits(b);
if (cntA == cntB)
return true ;
return false ;
}
public static void Main (String[] args)
{
int a = 3, b = 9;
if (isPossible(a, b))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function countSetBits(n)
{
if (n == 0)
return 0;
else
return (n & 1) + countSetBits(n >> 1);
}
function isPossible(a, b)
{
let cntA = countSetBits(a);
let cntB = countSetBits(b);
if (cntA == cntB)
return true ;
return false ;
}
let a = 3, b = 9;
if (isPossible(a, b))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...