
- 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
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 Articles
- Minimum flips required to maximize a number with k set bits in C++.
- Number of integers with odd number of 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++
- Check if all bits of a number are set in Python
- Reverse actual bits of the given number in Java
- 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
- Maximum number of contiguous array elements with same number of set bits in C++
- C# program to count total set bits in a number
- For every set bit of a number toggle bits of other in C++
- Check if a number has two adjacent set bits in C++
- How to count set bits in a floating point number in C?

Advertisements