Maximum distance between two 1 's in Binary representation of N | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longest_gap ( int N ) { int distance = 0 , count = 0 , first_1 = -1 , last_1 = -1 ; while ( N ) { count ++ ; int r = N & 1 ; if ( r == 1 ) { first_1 = first_1 == -1 ? count : first_1 ; last_1 = count ; } N = N / 2 ; } if ( last_1 <= first_1 ) { return -1 ; } else { distance = ( last_1 - first_1 - 1 ) ; return distance ; } } int main ( ) { int N = 131 ; cout << longest_gap ( N ) << endl ; N = 8 ; cout << longest_gap ( N ) << endl ; N = 17 ; cout << longest_gap ( N ) << endl ; N = 33 ; cout << longest_gap ( N ) << endl ; return 0 ; }