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
function countMaxSetBits ( left , right ) { let max_count = - 1 , num = 0 ; for ( let i = left ; i <= right ; ++ i ) { let temp = i , cnt = 0 ; while ( temp > 0 ) { if ( temp % 2 == 1 ) ++ cnt ; temp >>= 1 ; } if ( cnt > max_count ) { max_count = cnt ; num = i ; } } return num ; } let l = 1 , r = 5 ; document . write ( countMaxSetBits ( l , r ) + " " ) ; l = 1 ; r = 10 ; document . write ( countMaxSetBits ( l , r ) ) ;