Find the largest number smaller than integer N with maximum number of set bits | Java implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to get no of set bits in binary representation of positive integer n ; 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
class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } static int largestNum ( int n ) { int num = 0 ; int max_setBits = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { int setBits = countSetBits ( i ) ; if ( setBits >= max_setBits ) { num = i ; max_setBits = setBits ; } } return num ; } public static void main ( String [ ] args ) { int N = 345 ; System . out . println ( largestNum ( N ) ) ; } }