
- 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
Maximize the number by rearranging bits in C++
Problem statement
Given an unsigned number, find the maximum number that could be formed by using the bits of the given unsigned number
If the input number is 8 then its binary representation is−
00000000000000000000000000001000
To maximize it set MSB to 1. Then number becomes 2147483648 whose binary representation is−
10000000000000000000000000000000
Algorithms
1. Count number of set bits in the binary representation of a given number 2. Find a number with n least significant set bits 3. shift the number left by (32 – n)
Example
#include <bits/stdc++.h> using namespace std; unsigned getMaxNumber(unsigned num){ int n = __builtin_popcount(num); if (n == 32) { return num; } unsigned result = (1 << n) - 1; return (result << (32 - n)); } int main(){ unsigned n = 8; cout << "Maximum number = " << getMaxNumber(n) << endl; return 0; }
Output
When you compile and execute the above program. It generates the following output−
Maximum number = 2147483648
- Related Articles
- Maximize a given unsigned number by swapping bits at its extreme positions in C++
- Minimum flips required to maximize a number with k set bits in C++.
- Maximize number of 0s by flipping a subarray in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Rearranging digits to form the greatest number using JavaScript
- Maximize the number of sum pairs which are divisible by K in C++
- List all the numbers by rearranging the digits of 1546.
- Maximize the given number by replacing a segment of digits with the alternate digits given in C++
- Number of 1 Bits in Python
- Write the possible three digit numbers by rearranging the numbers(without repetition) : 2,5,9
- Maximum sum by adding numbers with same number of set bits in C++
- Rearranging array elements in JavaScript
- Maximize number of continuous Automorphic numbers in C++
- Reverse actual bits of the given number in Java
- Check whether an array can fit into another array by rearranging the elements in the array

Advertisements