Count 0 & 1 in Binary Representation

Count 0 & 1 in Binary Representation

 
Let’s say we have number 5 whose binary representation is 101. Now think of a way to calculate it’s 0’s and 1’s. You may be thinking to convert first number 5 into binary representation and then iterate the string.
 
But, when you are not allowed to convert your number into binary string then you need to think up of some other logic.
 
Number  Binary Representation

5               101
 
Expected output should be in this case : 0’s count : 1 and 1’s count : 2.
 
Here is the logic to calculate number of 0’s and 1’s.
 


package com.diaryreaders.java.bitwise;
/**
* @author Gaurav Gupta
*
*/
public class Binary01Count {
private static void count01(int n) {
int count0 = 0, count1 = 0;
while (n > 0) {
if (n % 2 == 0) {
count0++;
} else {
count1++;
}
n >>= 1;
}
System.out.println(count0);
System.out.println(count1);
}
public static void main(String[] args) {
count01(7);
}
}


 
Please comment if you have any problem to understand this.

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON