Check if all the set bits of the binary representation of N are at least K places away | C ++ program to check if all the set bits of the binary representation of N are at least K places away . ; Initialize check and count with 0 ; The i - th bit is a set bit ; This is the first set bit so , start calculating all the distances between consecutive bits from here ; If count is less than K return false ; Adding the count as the number of zeroes increase between set bits ; Driver code
#include <bits/stdc++.h> NEW_LINE 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 ; }