Smallest number whose set bits are maximum in a given range | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxSetBits ( int left , int right ) { int max_count = -1 , num ; for ( int i = left ; i <= right ; ++ i ) { int temp = i , cnt = 0 ; while ( temp ) { if ( temp & 1 ) ++ cnt ; temp >>= 1 ; } if ( cnt > max_count ) { max_count = cnt ; num = i ; } } return num ; } int main ( ) { int l = 1 , r = 5 ; cout << countMaxSetBits ( l , r ) << " STRNEWLINE " ; l = 1 , r = 10 ; cout << countMaxSetBits ( l , r ) ; return 0 ; }