如何计算二进制中的零数量?

huangapple go评论85阅读模式
英文:

How to calculate the number of zeros in binary?

问题

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;
}
英文:

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;
}

答案1

得分: 4

以下是解决这个问题的更简洁方法:

public static int binaryZeros(int n) {
    int zeroCount = 0;
    
    // 在 n 大于等于 1 的条件下运行循环
    while(n >= 1)
    {
        /* 使用取模运算符获得除以 2 的余数(由于你在进行除以 2 的运算,余数将为 1 或 0)。
           请记住,二进制表示是这些余数的数组,直到数字等于 1 为止。
           一旦数字等于 1,余数就是 1,因此你可以在那里退出循环。*/ 
        if(n % 2 == 0)
        {
            zeroCount++;
        }

        n = n / 2;
    }
    return zeroCount;
}
英文:

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;
}

答案2

得分: 2

你的方法不错,但我认为有一种更好的方法来做这件事。Integer类有一个静态方法可以返回一个数字的二进制形式:Integer.toBinaryString(num)。这将返回一个字符串。
然后,你可以使用一个带有循环的方法来检查该字符串中是否有任何0,并通过if语句进行评估:

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

我相信这将是一个更简单的选择,而且不会有任何错误。

英文:

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 &lt; binaryString.length; i++)
      if(binaryString.charAt[i].equals(&#39;0&#39;)
           zeros++;
return zeros;
}

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

答案3

得分: 1

一旦 m == 0.0,它将永远不会改变,因此你的 while 循环将永远不会停止。

英文:

Once m == 0.0, it will never change, so your while loop will never stop.

答案4

得分: 0

这里有一种方法。它简单地对整数的反转的二进制位进行补码运算,然后计算1的位数。在执行此操作时,不应使用浮点数运算。

  • ~ 对位进行补码运算
  • &1 屏蔽最低位。结果要么是1,要么是0
  • >>> 右移1位,包括符号位。
System.out.println(binaryZeros(44) + " (" +Integer.toBinaryString(44) +")"); 
System.out.println(binaryZeros(-44) + " (" +Integer.toBinaryString(-44)+")");
			
public static int binaryZeros(int v) {
    int count = 0;
    while (v != 0) {
        // 计算 ~v 的 1 位的数量
        count += (~v)&1;
        v >>>= 1;
    }
    return count;
}

输出

3 (101100)
4 (11111111111111111111111111010100)
英文:

Here is one way. It simply complements the integer reversing 1's and 0's and then counts the 1 bits. You should not be using floating point math when doing this.

  • ~ complements the bits
  • &amp;1 masks the low order bit. Is either 1 or 0
  • &gt;&gt;&gt; shifts right 1 bit including sign bit.
System.out.println(binaryZeros(44) + &quot; (&quot; +Integer.toBinaryString(44) +&quot;)&quot;); 
System.out.println(binaryZeros(-44) + &quot; (&quot;Integer.toBinaryString(-44)+&quot;)&quot;);
			
public static int binaryZeros(int v) {
	int count = 0;
	while (v != 0) {
        // count 1 bits 
        // of ~v
		count += (~v)&amp;1;
		v &gt;&gt;&gt;=1;
	}
	return count;
}

Prints

3 (101100)
4 (11111111111111111111111111010100)

</details>



# 答案5
**得分**: 0

```java
public static int getZeros(int num) {
    String str = Integer.toBinaryString(num);
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == '0') count++;
    }
    return count;
}

toBinaryString() 方法返回整数参数的无符号二进制字符串表示。它接受一个整数数据类型的参数,并返回相应的二进制字符串。
然后,for循环在字符串中计算零的数量并返回它。

英文:
public static int getZeros(int num) {
		String str= Integer.toBinaryString(num);
		int count=0;
		for(int i=0; i&lt;str.length(); i++) {
			if(str.charAt(i)==&#39;0&#39;) count++;
		}
		return count;
	}

The method toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Then the for loop counts the number of zeros in the String and returns it.

答案6

得分: 0

如果你从一个大于或等于 0 的数字 m 开始,无论你如何多次将它除以 2 或使用 Math.floor,它永远不会变为负数。循环应该在 m 达到 0 时停止,所以将条件改为 while (m > 0.0)

请注意,你也可以使用内置的标准库方法来做同样的事情。例如,有一个方法可以返回数字中前导零的数量,还有一个方法可以返回数字中位为 1 的数量。通过同时使用这两个方法,你可以计算出非前导零的零的数量:

static int binaryZeros(int n) {
    return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}
英文:

If you start with a number m >= 0, it can never become negative no matter how many times you divide it by 2 or use Math.floor. The loop should stop when m reaches 0, so change the condition to while (m &gt; 0.0).

Note that you could do the same thing with built-in standard library methods. For example, there is a method that returns the number of leading zeros in a number, and a method that returns the number of bits set to 1. Using both you can compute the number of zeros that are not leading zeros:

static int binaryZeros(int n) {
    return Integer.SIZE - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n);
}

答案7

得分: 0

只要简单地使用Integer.bitCount(n)方法:

public static int binaryZeros(int n) {
    long val = n & 0xFFFFFFFFL;
    int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
    int setBits = Long.bitCount(val);
    return totalBits - setBits;
}
英文:

Just be simple, whe there's Integer.bitCount(n) method:

public static int binaryZeros(int n) {
    long val = n &amp; 0xFFFFFFFFL;
    int totalBits = (int)(Math.log(val) / Math.log(2) + 1);
    int setBits = Long.bitCount(val);
    return totalBits - setBits;
}

huangapple
  • 本文由 发表于 2020年8月19日 01:37:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63473870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定