# Minimum number using set bits of a given number in C++

C++Server Side ProgrammingProgramming

## 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

Live Demo

#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
Published on 23-Dec-2019 06:10:50