Maximum distance between two 1 's in Binary representation of N | Javascript program to find the Maximum distance between two 1 's in Binary representation of N ; Compute the binary representation ; if N is a power of 2 then return - 1 ; else find the distance between the first position of 1 and last position of 1 ; Driver code
function longest_gap ( N ) { let distance = 0 , count = 0 , first_1 = - 1 , last_1 = - 1 ; while ( N ) { count ++ ; let r = N & 1 ; if ( r == 1 ) { first_1 = first_1 == - 1 ? count : first_1 ; last_1 = count ; } N = parseInt ( N / 2 ) ; } if ( last_1 <= first_1 ) { return - 1 ; } else { distance = ( last_1 - first_1 - 1 ) ; return distance ; } } let N = 131 ; document . write ( longest_gap ( N ) + " " ) ; N = 8 ; document . write ( longest_gap ( N ) + " " ) ; N = 17 ; document . write ( longest_gap ( N ) + " " ) ; N = 33 ; document . write ( longest_gap ( N ) + " " ) ;