Check if all the set bits of the binary representation of N are at least K places away | Javascript 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
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 ( " " ) ; } else { document . write ( " " ) ; }