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


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.

We will do this by traversing no. from i=0 to i<=X and for each i, if (i+X==i^X) then increment count.

Let us understand with examples.

Input − X=6

Output − Count of numbers whose sum with X == XOR with X: 2

Explanation − Numbers are 0 and 1 only.

Input − X=20

Output − Count of numbers whose sum with X == XOR with X: 8

Explanation − Numbers are 0 1 2 3 8 9 10 11

Approach used in the below program is as follows

  • We take integer X.

  • Function sumisXOR(int x) takes x and returns a count of numbers whose sum with x is equal to xor with x.

  • Take the initial count as 0.

  • Traverse from i=0 to i<=x.

  • If i+x==i^x. Increment count

  • At the end of for loop count will have the desired result...

  • Return count and print.

Example

 Live Demo

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int sumisXOR(int x){
   int count = 0;
   for (int i = 0; i <= x; i++){
      if((i+x)==(i^x))
         { count++; }
   }
   return count;
}
int main(){
   int X = 15;
   int nums=sumisXOR(X);
   cout <<endl<<"Count of numbers whose sum with X == XOR with X: "<<nums;
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of numbers whose sum with X == XOR with X: 1

Updated on: 31-Oct-2020

87 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements