VOOZH about

URL: https://www.geeksforgeeks.org/dsa/xor-counts-0s-1s-binary-representation/

⇱ XOR counts of 0s and 1s in binary representation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

XOR counts of 0s and 1s in binary representation

Last Updated : 23 Jul, 2025

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.


 

Recommended Practice


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

Output: 

5

Time Complexity: O(log(N))
Auxiliary Space: O(1)


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
 


 

Comment
Article Tags: