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
function countSetBits ( n ) { let count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } function largestNum ( n ) { let num = 0 ; let max_setBits = 0 ; for ( let i = 0 ; i <= n ; i ++ ) { let setBits = countSetBits ( i ) ; if ( setBits >= max_setBits ) { num = i ; max_setBits = setBits ; } } return num ; } let N = 345 ; document . write ( largestNum ( N ) ) ;