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
Minimum number using set bits of a given number in C++
Problem statement
Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number.
Example
If input = 10 then answer would be 3
Binary representation of 10 is 1010 and minimum number with 2 set bits is 0011 i.e. 3
Algorithm
1. Count the number of set bits. 2. (Number of set bits) ^ 2 – 1 represents the minimized number)
Example
#include <bits/stdc++.h>
using namespace std;
int getSetBits(int n) {
int cnt = 0;
while (n) {
++cnt;
n = n & (n - 1);
}
return cnt;
}
int getMinNumber(int n){
int bits = getSetBits(n);
return pow(2, bits) - 1;
}
int main() {
int n = 10;
cout << "Minimum number = " << getMinNumber(n) << endl;
return 0;
return 0;
}
When you compile and execute above program. It generates following output
Output
Minimum number = 3
Advertisements