 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements
 