Smallest number whose set bits are maximum in a given range | 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
< ? php function countMaxSetBits ( $ left , $ right ) { $ max_count = -1 ; $ num ; for ( $ i = $ left ; $ i <= $ right ; ++ $ i ) { $ temp = $ i ; $ cnt = 0 ; while ( $ temp ) { if ( $ temp & 1 ) ++ $ cnt ; $ temp >>= 1 ; } if ( $ cnt > $ max_count ) { $ max_count = $ cnt ; $ num = $ i ; } } return $ num ; } $ l = 1 ; $ r = 5 ; echo countMaxSetBits ( $ l , $ r ) , " STRNEWLINE " ; $ l = 1 ; $ r = 10 ; echo countMaxSetBits ( $ l , $ r ) ; ? >