Smallest number whose set bits are maximum in a given range | Java program 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
class gfg { static int countMaxSetBits ( int left , int right ) { int max_count = - 1 , num = 0 ; for ( int i = left ; i <= right ; ++ i ) { int 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 ; } public static void main ( String [ ] args ) { int l = 1 , r = 5 ; System . out . println ( countMaxSetBits ( l , r ) ) ; l = 1 ; r = 10 ; System . out . print ( countMaxSetBits ( l , r ) ) ; } }