
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Check if a number has same number of set and unset bits in C++
- Program to find higher number with same number of set bits as n in Python?\n
- Count unset bits of a number in C++
- Find largest number smaller than N with same set of digits in C++
- Largest number less than X having at most K set bits in C++
- Count unset bits in a range in C++
- Find the number with set bits only between L-th and R-th index using C++
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Find all combinations of k-bit numbers with n bits set where 1
- Python program to count unset bits in a range.
- Largest number with the given set of N digits that is divisible by 2, 3 and 5 in C++
- Largest set with bitwise OR equal to n in C++
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Find the largest good number in the divisors of given number N in C++

Advertisements