Maximize the number by rearranging bits in C++

C++Server Side ProgrammingProgramming

<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&minus;</p><pre class="result notranslate">00000000000000000000000000001000</pre><p>To maximize it set MSB to 1. Then number becomes 2147483648 whose binary representation is&minus;</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 &ndash; n)</pre><h2>Example</h2><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">#include &lt;bits/stdc++.h&gt; using namespace std; unsigned getMaxNumber(unsigned num){ &nbsp; &nbsp;int n = __builtin_popcount(num); &nbsp; &nbsp;if (n == 32) { &nbsp; &nbsp; &nbsp; return num; &nbsp; &nbsp;} &nbsp; &nbsp;unsigned result = (1 &lt;&lt; n) - 1; &nbsp; &nbsp;return (result &lt;&lt; (32 - n)); } int main(){ &nbsp; &nbsp;unsigned n = 8; &nbsp; &nbsp;cout &lt;&lt; &quot;Maximum number = &quot; &lt;&lt; getMaxNumber(n) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>When you compile and execute the above program. It generates the following output&minus;</p><pre class="result notranslate">Maximum number = 2147483648</pre>
Updated on 24-Dec-2019 07:09:42