Equal Sum and XOR in C++


In this problem, we are given an integer n. Our task is to create a program to find the count of integers from i = 0 to n, where sum is equal to XOR i.e. (n+i) = (n^i).

Let’s take an example to understand the problem,

Input:  n = 4

Output: 4

Explanation: 

Considering all values of i from 0 to n,

i = 0,  4 + 0 = 4, 4^0 = 4
i = 1,  4 + 1 = 5, 4^1 = 5
i = 2,  4 + 2 = 6, 4^2 = 6
i = 3,  4 + 3 = 7, 4^3 = 7
i = 4,  4 + 4 = 8, 4^4 = 0
Count = 4

Solution Approach:

A simple solution is to find the values of the sum of n and i and xor of n and i. Compare both these values and then count the values for which they are equal.

Algorithm:

Step 1: Loop for all values from i = 0 to n.

Step 1.1: Find the value of (n + i).

Step 1.2: Find the value of (n^i).

Step 1.3: compare values found in step 1.1 and 1.2.
Step 1.4: If they are equal, increase count.

Step 2: Print count values.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

int main() {
   
   int n = 5;
   int counter = 0;
   for(int i=0; i<=n; i++ )
      if ( (n+i) == (n^i) )
         counter++;
   cout<<"The count of integers with equal sum and XOR is "<<counter;
   return 0;
}

Output −

The count of integers with equal sum and XOR is 2

The method is good but their can be a better solution to the problem, which is using the fact that

If n^i = n+i, then n&i = 0.

If the value of n&i = 0, for that we need the two numbers to have opposite set and unset bits. And we need to count such values. Here is a program to do it,

Example

Live Demo

#include <iostream>
using namespace std;

int countValuesWithEqualSumXOR(int n) {
   
   int countUnSetBits=0;
   while (n) {
      if ((n & 1) == 0)
         countUnSetBits++;
      n=n>>1;
   }
   return 1 << countUnSetBits;
}

int main()
{
   int n = 6;
   cout<<"The count of integers with equal sum and XOR is "<<countValuesWithEqualSumXOR(n);
   return 0;
}

Output −

The count of integers with equal sum and XOR is 2

Updated on: 22-Jan-2021

693 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements