

- 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
Maximize the number by rearranging bits in C++
<h2 style="">Problem statement</h2><p>Given an unsigned number, find the maximum number that could be formed by using the bits of the given unsigned number</p><p style="">If the input number is 8 then its binary representation is−</p><pre class="result notranslate">00000000000000000000000000001000</pre><p>To maximize it set MSB to 1. Then number becomes 2147483648 whose binary representation is−</p><pre class="result notranslate">10000000000000000000000000000000</pre><h2>Algorithms</h2><pre class="result notranslate">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)</pre><h2>Example</h2><p><a class="demo" href="http://tpcg.io/24lGluOy" rel="nofollow" target="_blank"> Live Demo</a></p><pre class="prettyprint notranslate" style="">#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; }</pre><h2>Output</h2><p>When you compile and execute the above program. It generates the following output−</p><pre class="result notranslate">Maximum number = 2147483648</pre>
- Related Questions & Answers
- 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++.
- Rearranging digits to form the greatest number using JavaScript
- Maximize number of 0s by flipping a subarray in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Maximize the number of sum pairs which are divisible by K in C++
- Maximize the given number by replacing a segment of digits with the alternate digits given in C++
- Rearranging array elements in JavaScript
- Number of 1 Bits in Python
- Maximum sum by adding numbers with same number of set bits in C++
- Maximize the profit by selling at-most M products in C++
- Reverse actual bits of the given number in Java
- Rearranging cards into groups in JavaScript
- Rearrange the string to maximize the number of palindromic substrings in C++
- Maximize number of continuous Automorphic numbers in C++
Advertisements