text: Largest number with binary representation is m 1 's and m | CPP program to find largest number smaller than equal to n with m set bits then m - 1 0 bits . ; Returns largest number with m set bits then m - 1 0 bits . ; Start with 2 bits . ; initial answer is 1 which meets the given condition ; check for all numbers ; compute the number ; if less then N ; increment m to get the next number ; driver code to check the above condition
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; long long answer ( long long n ) { long m = 2 ; long long ans = 1 ; long long r = 1 ; while ( r < n ) { r = ( int ) ( pow ( 2 , m ) - 1 ) * ( pow ( 2 , m - 1 ) ) ; if ( r < n ) ans = r ; m ++ ; } return ans ; } int main ( ) { long long n = 7 ; cout << answer ( n ) ; return 0 ; }