XOR counts of 0s and 1s in binary representation in C++


In this problem, we are given a number. Our task is to find the XOR of the count of 0s and 1s in the binary representation of the number.

Let’s take an example to understand the problem,

Input

n = 9

Output

0

Explanation

binary = 1001
Count of 0s = 2
Count of 1s = 2
2 ^ 2 = 0

To solve this problem, we will first convert the number of its binary equivalent and then iterating over each bit of the number, count 0s, and 1s and then find XOR of the count of 0s and count of 1s.

Program to illustrate the above solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int countXOR10(int n) {
   int count0s = 0, count1s = 0;
   while (n){
      (n % 2 == 0) ? count0s++ :count1s++;
      n /= 2;
   }
   return (count0s ^ count1s);
}
int main() {
   int n = 21;
   cout<<"XOR of count of 0s and 1s in binary of "<<n<<" is "<<countXOR10(n);
   return 0;
}

Output

XOR of count of 0s and 1s in binary of 21 is 1

Updated on: 17-Apr-2020

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements