Check if all the set bits of the binary representation of N are at least K places away
Given numbers N and K, The task is to check if all the set bits of the binary representation of N are at least K places away.
Examples:
Input: N = 5, K = 1
Output: YES
Explanation:
Binary of 5 is 101.
The 1's are 1 place far from each other.
Input: N = 10, K = 2
Output: NO
Explanation:
Binary of 10 is 1010.
The 1's are not at least 2 places far from each other.
Approach:
- Iterate Over all the bits in the binary representation of N and maintain a variable ‘count’ initialize to 0.
- Whenever you find a set bit(1), check if count <= K. If not return false.
- If you find a unset bit(0), increases the value of count by 1.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
bool CheckBits( int N, int K)
{
int check = 0;
int count = 0;
for ( int i = 31; i >= 0; i--)
{
if ((1 << i) & N)
{
if (check == 0)
{
check = 1;
}
else
{
if (count < K)
{
return false ;
}
}
count = 0;
}
else
{
count++;
}
}
return true ;
}
int main()
{
int N = 5;
int K = 1;
if (CheckBits(N, K))
{
cout << "YES" ;
}
else
{
cout << "NO" ;
}
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean CheckBits( int N, int K)
{
int check = 0 ;
int count = 0 ;
for ( int i = 31 ; i >= 0 ; i--)
{
if ((( 1 << i) & N) > 0 )
{
if (check == 0 )
{
check = 1 ;
}
else
{
if (count < K)
{
return false ;
}
}
count = 0 ;
}
else
{
count++;
}
}
return true ;
}
public static void main(String[] args)
{
int N = 5 ;
int K = 1 ;
if (CheckBits(N, K))
{
System.out.print( "YES" );
}
else
{
System.out.print( "NO" );
}
}
}
|
Python3
def CheckBits(N, K):
check = 0
count = 0
for i in range ( 31 , - 1 , - 1 ):
if (( 1 << i) & N):
if (check = = 0 ):
check = 1
else :
if (count < K):
return False
count = 0
else :
count + = 1
return True
if __name__ = = "__main__" :
N = 5
K = 1
if (CheckBits(N, K)):
print ( "YES" )
else :
print ( "NO" )
|
C#
using System;
public class GFG{
static bool CheckBits( int N, int K)
{
int check = 0;
int count = 0;
for ( int i = 31; i >= 0; i--)
{
if (((1 << i) & N) > 0)
{
if (check == 0)
{
check = 1;
}
else
{
if (count < K)
{
return false ;
}
}
count = 0;
}
else
{
count++;
}
}
return true ;
}
static public void Main ()
{
int N = 5;
int K = 1;
if (CheckBits(N, K))
{
Console.Write( "YES" );
}
else
{
Console.Write( "NO" );
}
}
}
|
Javascript
<script>
function CheckBits(N, K)
{
var check = 0;
var count = 0;
for ( var i = 31; i >= 0; i--)
{
if (((1 << i) & N) > 0)
{
if (check == 0)
{
check = 1;
}
else
{
if (count < K)
{
return false ;
}
}
count = 0;
}
else
{
count++;
}
}
return true ;
}
var N = 5;
var K = 1;
if (CheckBits(N, K))
{
document.write( "YES" );
}
else
{
document.write( "NO" );
}
</script>
|
Time complexity: O(1)
Auxiliary space: O(1)
Last Updated :
21 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...