XOR counts of 0s and 1s in binary representation

1.7

Given a number, the task is to find XOR of count of 0s and count of 1s in binary representation of a given number.
Examples:

Input  : 5
Output : 3
Binary representation : 101
Count of 0s = 1, 
Count of 1s = 2
1 XOR 2 = 3.

Input  : 7
Output : 3
Binary representation : 111
Count of 0s = 0
Count of 1s = 3
0 XOR 3 = 3.

The idea is simple, we traverse through all bits of a number, count 0s and 1s and finally return XOR of two counts.

// C++ program to find XOR of counts 0s and 1s in
// binary representation of n.
#include<iostream>
using namespace std;

// Returns XOR of counts 0s and 1s in
// binary representation of n.
int countXOR(int n)
{
    int count0 = 0, count1 = 0;
    while (n)
    {
        //calculating count of zeros and ones
        (n % 2 == 0) ? count0++ :count1++;
        n /= 2;
    }
    return (count0 ^ count1);
}

// Driver Program
int main()
{
    int n = 31;
    cout << countXOR (n);
    return 0;
}

Output:

 5

One observation is, for a number of the form 2^x – 1, the output is always x. We can directly produce answer for this case by first checking n+1 is a power of two or not.

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.7 Average Difficulty : 1.7/5.0
Based on 4 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.