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 possible values ; Multiply the number by 2 i times ; Return the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int n ) { int num = 0 ; for ( int i = 0 ; i <= 32 ; i ++ ) { int x = ( 1 << i ) ; if ( ( x - 1 ) <= n ) num = ( 1 << i ) - 1 ; else break ; } return num ; } int main ( ) { int N = 345 ; cout << largestNum ( N ) ; return 0 ; }