Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of zeros in binary?

Tags:

java

binary

Hi I am making a method that can take an integer as a parameter and compute how many zeros its binary form has. So for example, if I have binaryZeros(44), its binary form is 101100. Therefore, binaryZeros(44) should return 3. However, I am making some errors and I cannot tell where it is coming from. I would appreciate it if someone can point out where I am making that error, or if my approach (logic) to this problem is good enough. Thank you! My code is Below:

public static int binaryZeros(int n) {
int zeroCount = 0;
double m = n;
while (m >= 0.0) {
    m = m / 2.0;
    if (m == Math.floor(m)) {
        zeroCount++;
    } else {
        m = Math.floor(m);
    }
}
return zeroCount;
}
like image 381
NikoHH Avatar asked Oct 20 '25 05:10

NikoHH


2 Answers

Below is a more concise way to solve this problem

public static int binaryZeros(int n) {
    int zeroCount = 0;
    
    // Run a while loop until n is greater than or equals to 1
    while(n >= 1)
    {
        /* Use modulo operator to get the reminder of division by 2 (reminder will be 1 or 0 as you are dividing by 2). 
           Keep in mind that binary representation is an array of these reminders until the number is equal to 1. 
           And once the number is equal to 1 the reminder is 1, so you can exit the loop there.*/ 
        if(n % 2 == 0)
        {
            zeroCount++;
        }

        n = n / 2;
    }
    return zeroCount;
}
like image 95
ab_ Avatar answered Oct 21 '25 20:10

ab_


Your approach is good, but I think there's a better way to do it. The Integer class has a static method that returns the binary of a number: Integer.toBinaryString(num) . This will return a String. Then, you can just check if there are any 0 in that string with method that has a for loop and evaluating with an if:

public int getZeros(String binaryString){
int zeros = 0;
for(int i=0; i < binaryString.length; i++)
      if(binaryString.charAt[i].equals('0')
           zeros++;
return zeros;
}

I believe this would be a simpler option and it doesn't have any errors.

like image 26
JeroSquartini Avatar answered Oct 21 '25 20:10

JeroSquartini