- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Calculating 1s in binary representation of numbers in JavaScript
- Count all 0s which are blocked by 1s in binary matrix in C++
- Count numbers have all 1s together in binary representation in C++
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Largest subarray with equal number of 0s and 1s in C++
- Sorting according to number of 1s in binary representation using JavaScript
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Minimum toggles to partition a binary array so that it has first 0s then 1s in C++
- C Program to construct DFA accepting odd numbers of 0s and 1s
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Minimum flips to make all 1s in left and 0s in right in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Python - List Initialization with alternate 0s and 1s

Advertisements