Count numbers whose sum with x is equal to XOR with x in C++

C++Server Side ProgrammingProgramming

<p>We are a number X. The goal is to find numbers between 0 and X whose sum with X is equal to XOR with X.</p><p>We will do this by traversing no. from i=0 to i&lt;=X and for each i, if (i+X==i^X) then increment count.</p><p>Let us understand with examples.</p><p><strong>Input</strong> &minus; X=6</p><p><strong>Output</strong> &minus; Count of numbers whose sum with X == XOR with X: 2</p><p><strong>Explanation</strong> &minus; Numbers are 0 and 1 only.</p><p><strong>Input</strong> &minus; X=20</p><p><strong>Output</strong> &minus; Count of numbers whose sum with X == XOR with X: 8</p><p><strong>Explanation</strong> &minus; Numbers are 0 1 2 3 8 9 10 11</p><h2>Approach used in the below program is as follows</h2><ul class="list"><li><p>We take integer X.</p></li><li><p>Function sumisXOR(int x) takes x and returns a count of numbers whose sum with x is equal to xor with x.</p></li><li><p>Take the initial count as 0.</p></li><li><p>Traverse from i=0 to i&lt;=x.</p></li><li><p>If i+x==i^x. Increment count</p></li><li><p>At the end of for loop count will have the desired result...</p></li><li><p>Return count and print.</p></li></ul><h2>Example</h2><p><a class="demo" href="http://tpcg.io/Oqwb2HYK" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include &lt;bits/stdc++.h&gt; #include &lt;math.h&gt; using namespace std; int sumisXOR(int x){ &nbsp; &nbsp;int count = 0; &nbsp; &nbsp;for (int i = 0; i &lt;= x; i++){ &nbsp; &nbsp; &nbsp; if((i+x)==(i^x)) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ count++; } &nbsp; &nbsp;} &nbsp; &nbsp;return count; } int main(){ &nbsp; &nbsp;int X = 15; &nbsp; &nbsp;int nums=sumisXOR(X); &nbsp; &nbsp;cout &lt;&lt;endl&lt;&lt;&quot;Count of numbers whose sum with X == XOR with X: &quot;&lt;&lt;nums; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>If we run the above code it will generate the following output &minus;</p><pre class="result notranslate">Count of numbers whose sum with X == XOR with X: 1</pre>
raja
Updated on 31-Oct-2020 05:26:37

Advertisements