

- 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
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
- Related Questions & Answers
- Number of integers with odd number of set bits in C++
- Minimum flips required to maximize a number with k set bits in C++.
- Next higher number with same number of set bits in C++
- Convert a number m to n using minimum number of given operations in C++
- Check if a number has same number of set and unset bits in C++
- Reverse actual bits of the given number in Java
- Check if all bits of a number are set in Python
- Maximum number of contiguous array elements with same number of set bits in C++
- Prime Number of Set Bits in Binary Representation in C++
- Prime Number of Set Bits in Binary Representation in Python
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Minimum number of coins that make a given value
- C# program to count total set bits in a number
- For every set bit of a number toggle bits of other in C++
- Minimum number of squares whose sum equals to given number n
Advertisements