Maximum distance between two 1 's in Binary representation of N | Python3 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
def longest_gap ( N ) : NEW_LINE INDENT distance = 0 NEW_LINE count = 0 NEW_LINE first_1 = - 1 NEW_LINE last_1 = - 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE r = N & 1 NEW_LINE if ( r == 1 ) : NEW_LINE INDENT if first_1 == - 1 : NEW_LINE INDENT first_1 = count NEW_LINE DEDENT else : NEW_LINE INDENT first_1 = first_1 NEW_LINE DEDENT last_1 = count NEW_LINE DEDENT N = N // 2 NEW_LINE DEDENT if ( last_1 <= first_1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT distance = last_1 - first_1 - 1 NEW_LINE return distance NEW_LINE DEDENT DEDENT N = 131 NEW_LINE print ( longest_gap ( N ) ) NEW_LINE N = 8 NEW_LINE print ( longest_gap ( N ) ) NEW_LINE N = 17 NEW_LINE print ( longest_gap ( N ) ) NEW_LINE N = 33 NEW_LINE print ( longest_gap ( N ) ) NEW_LINE