Find the largest number smaller than integer N with maximum number of set bits | C ++ implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int n ) { int num = 0 ; int max_setBits = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { int setBits = __builtin_popcount ( i ) ; if ( setBits >= max_setBits ) { num = i ; max_setBits = setBits ; } } return num ; } int main ( ) { int N = 345 ; cout << largestNum ( N ) ; return 0 ; }