Find smallest number n such that n XOR n+1 equals to given k in C++

C++Server Side ProgrammingProgramming

<p>Suppose we have a positive number k. We have to find the positive number n, such that XOR of n and n+1 is same as k. So if k = 7 (111), output will be 3. As 3 (011), and 3 + 1 = 4 (100), so 011 XOR 100 = 111 (7)</p><p>There are two possible cases. Consider n is even. The last bit of n = 0. Then the last bit of n + 1 = 1. Rest of the bits are same. So XOR will be 1, when n is odd, last bit 1, and last bit of n + 1 bit is 0. But in this case, more bits which differ due to carry. The carry continues to propagate to left till we get first 0 bit. So n XOR n + 1, will be 2^i -1, where i is the position of first 0 bit in n from left. So we can say that if k is of the form 2^i &ndash; 1, the answer will be k/2.</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/60v7wR6n" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include&lt;iostream&gt; using namespace std; int findNValue(int k) { &nbsp; &nbsp;if (k == 1) &nbsp; &nbsp; &nbsp; return 2; &nbsp; &nbsp;if (((k + 1) &amp; k) == 0) &nbsp; &nbsp; &nbsp; return k / 2; &nbsp; &nbsp; &nbsp; return -1; } int main() { &nbsp; &nbsp;int k = 15; &nbsp; &nbsp;cout &lt;&lt; &quot;The value of n is: &quot; &lt;&lt; findNValue(k); }</pre><h2>Output</h2><pre class="result notranslate">The value of n is: 7</pre>
raja
Updated on 18-Dec-2019 10:49:07

Advertisements