Maximum Bitwise AND pair from given range in C++

C++Server Side ProgrammingProgramming

<h2>Problem statement</h2><p>Given a range [L, R], the task is to find a pair (X, Y) such that L &le; X &lt; Y &le; R and X &amp; Y is maximum among all the possible pairs then print the bitwise AND of the found pair.</p><h2>Example</h2><p>If L = 1 and R = 10 then maximum bitwise AND value is 8 which can be formed as follows &minus;</p><pre class="result notranslate">1000 # Binary representation of 8 Bitwise AND 1001 # Binary representation of 9 ---- 1000 # Final result</pre><h2>Algorithm</h2><p>Iterate from L to R and check the bitwise AND for every possible pair and print the maximum value in the ends</p><h2>Example</h2><p>Let us now see an example &minus;</p><p><a class="demo" href="http://tpcg.io/YtJ0XMmw" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;bits/stdc++.h&gt; using namespace std; int getMaxBitwiseAndValue(int L, int R) { &nbsp; &nbsp;int maxValue = L &amp; R; &nbsp; &nbsp;for (int i = L; i &lt; R; ++i) { &nbsp; &nbsp; &nbsp; for (int j = i + 1; j &lt;= R; ++j) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;maxValue = max(maxValue, (i &amp; j)); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return maxValue; } int main() { &nbsp; &nbsp;int L = 1, R = 10; &nbsp; &nbsp;cout &lt;&lt; &quot;Maximum value = &quot; &lt;&lt; getMaxBitwiseAndValue(L, R) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">Maximum value = 8</pre>
raja
Updated on 31-Dec-2019 12:19:58

Advertisements