Smallest number whose set bits are maximum in a given range | Python code to find number whose set bits are maximum among ' l ' and 'r ; Returns smallest number whose set bits are maximum in given range . ; Initialize the maximum count and final answer as ' num ' ; Traverse for every bit of ' i ' number ; If count is greater than previous calculated max_count , update it ; driver code
' NEW_LINE def countMaxSetBits ( left , right ) : NEW_LINE INDENT max_count = - 1 NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT temp = i NEW_LINE cnt = 0 NEW_LINE while temp : NEW_LINE INDENT if temp & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT temp = temp >> 1 NEW_LINE DEDENT if cnt > max_count : NEW_LINE INDENT max_count = cnt NEW_LINE num = i NEW_LINE DEDENT DEDENT return num NEW_LINE DEDENT l = 1 NEW_LINE r = 5 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_LINE l = 1 NEW_LINE r = 10 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_LINE