
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements