Find the possible permutation of the bits of N
Last Updated :
13 Mar, 2022
Given an integer N, the task is to find whether the bits of N can be arranged in alternating manner i.e. either 0101… or 10101…. Assume that N is represented as a 32 bit integer.
Examples:
Input: N = 23
Output: No
“00000000000000000000000000010111” is the binary representation of 23
and the required permutation of bits is not possible.
Input: N = 524280
Output: Yes
binary(524280) = “00000000000001111111111111111000” which can be
rearranged to “01010101010101010101010101010101”.
Approach: Since the given integer has to be represented in 32 bits and the number of 1s must be equal to the number of 0s in its binary representation to satisfy the given condition. So, the number of set bits in N must be 16 which can be easily calculated using __builtin_popcount()
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int TOTAL_BITS = 32;
bool isPossible( int n)
{
int cnt = __builtin_popcount(n);
if (cnt == TOTAL_BITS / 2)
return true ;
return false ;
}
int main()
{
int n = 524280;
if (isPossible(n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int TOTAL_BITS = 32 ;
static boolean isPossible( int n)
{
int cnt = Integer.bitCount(n);
if (cnt == TOTAL_BITS / 2 )
return true ;
return false ;
}
static public void main (String []arr)
{
int n = 524280 ;
if (isPossible(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
TOTAL_BITS = 32 ;
def isPossible(n) :
cnt = bin (n).count( '1' );
if (cnt = = TOTAL_BITS / / 2 ) :
return True ;
return False ;
if __name__ = = "__main__" :
n = 524280 ;
if (isPossible(n)) :
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
class GFG
{
static int TOTAL_BITS = 32;
static int CountBits( int value)
{
int count = 0;
while (value != 0)
{
count++;
value &= value - 1;
}
return count;
}
static bool isPossible( int n)
{
int cnt = CountBits(n);
if (cnt == TOTAL_BITS / 2)
return true ;
return false ;
}
public static void Main (String []arr)
{
int n = 524280;
if (isPossible(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
const TOTAL_BITS = 32;
function CountBits(value)
{
let count = 0;
while (value != 0)
{
count++;
value &= value - 1;
}
return count;
}
function isPossible(n)
{
let cnt = CountBits(n);
if (cnt == parseInt(TOTAL_BITS / 2))
return true ;
return false ;
}
let n = 524280;
if (isPossible(n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...