Find the largest number with n set and m unset bits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two integer values, n and m. Our task is to find the largest number with n set and m unset bits in the binary representation of the number.

Let's take an example to understand the problem

Input : n = 3, m = 1
Output : 14

Explanation

Largest number will have 3 set bits and then 1 unset bit.
(1110)2 = 14

Solution Approach

A simple solution to the problem is by finding the number consisting of (n+m) set bits. From this number, toggle off the m bits from the end (LSB). To create a number with (n+m) set bits,

$$(1\ll(n+m))-1$$

Then toggle m bits and return the number.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
int findlargestNumber(int n, int m){
   int maxNum = (1 << (n + m)) - 1;
   if (m == 0)
      return maxNum;
   int number = (1 << m) - 1;
   return (maxNum ^ number);
}
int main(){
   int n = 5,
   m = 2;
   cout<<"The largest number with "<<n<<" set bits and "<<m<<" unset bits is "<<findlargestNumber(n, m);
   return 0;
}

Output

The largest number with 5 set bits and 2 unset bits is 124
raja
Updated on 28-Jan-2022 11:28:26

Advertisements