text: Largest number with binary representation is m 1 's and m | Python3 program to find largest number smaller than equal to n with m set bits then m - 1 0 bits . ; Returns largest number with m set bits then m - 1 0 bits . ; Start with 2 bits . ; initial answer is 1 which meets the given condition ; check for all numbers ; compute the number ; if less then N ; increment m to get the next number ; Driver Code
code: import math NEW_LINE def answer ( n ) : NEW_LINE INDENT m = 2 ; NEW_LINE ans = 1 ; NEW_LINE r = 1 ; NEW_LINE while r < n : NEW_LINE INDENT r = ( int ) ( ( pow ( 2 , m ) - 1 ) * ( pow ( 2 , m - 1 ) ) ) ; NEW_LINE if r < n : NEW_LINE INDENT ans = r ; NEW_LINE DEDENT m = m + 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT print ( answer ( 7 ) ) ; NEW_LINE