- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- Related Questions & Answers
- Check if a number has same number of set and unset bits in C++
- Count unset bits of a number in C++
- Program to find higher number with same number of set bits as n in Python?
- Find largest number smaller than N with same set of digits in C++
- Find the number closest to n and divisible by m in C++
- Find a positive number M such that gcd(N^M,N&M) is maximum in Python
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Find the number with set bits only between L-th and R-th index using C++
- Find the largest good number in the divisors of given number N in C++
- Count unset bits in a range in C++
- Largest number less than X having at most K set bits in C++
- Largest number with the given set of N digits that is divisible by 2, 3 and 5 in C++
- Find the minimum number of steps to reach M from N in C++
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++

Advertisements