整数中除了前导零外的零位数目

4

如果我在Java中有一个整数,如何计算除前导零外有多少个零位?

我们知道Java中的整数有32位,但是仅仅计算数字中设置的位数然后从32中减去并不能给我想要的结果,因为这也会包括前导零。

例如,数字5有一个零位,因为它在二进制中是101


我根据对我的原始答案发表的评论编辑了问题。 - Mark Byers
请参见:http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#bitCount(int) 和 http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#numberOfLeadingZeros(int)。 - laura
6个回答

7

请查看Integer的API文档:

32 - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n)

3
为了在Java中计算非前导零,您可以使用以下算法:
public static int countNonleadingZeroBits(int i)
{
    int result = 0;
    while (i != 0)
    {
        if (i & 1 == 0)
        {
            result += 1;
        }
        i >>>= 1;
    } 
    return result;
}

如果您的输入通常较小,则此算法将相对较快,但如果您的输入通常是一个较大的数字,则使用此页面上的位计算算法变体可能会更快。请参考此页面了解详细信息。

1
@davit-datuashvili: 所以您想要计算除前导零之外的零吗? - Mark Byers
5 = 000...000101。你想要的是最后一个(最高位)被设置的位数加一,再减去被设置的位数。 - ony
这个不处理负数。也许 >>> 1 而不是 /= 2 是一个更好的选择。 - Peter Lawrey

1

这就是我会做的。

public static int countBitsSet(int num) {
    int count = num & 1; // start with the first bit.
    while((num >>>= 1) != 0) // shift the bits and check there are some left.
        count += num & 1; // count the next bit if its there.
    return count;
}

public static int countBitsNotSet(int num) {
    return 32 - countBitsSet(num);
}

“32-x” 不是 OP 想要的。被计算的位不全是 32,只有最后一个设置的位。 (他在原问题中没有解释清楚) - Stephen

1

计算您的数字中“位”(bits)的总数,然后从位数总数中减去1的数量。


0
使用一些内置函数:
public static int zeroBits(int i)
{
    if (i == 0) {
        return 0;
    }
    else {
        int highestBit = (int) (Math.log10(Integer.highestOneBit(i)) / 
                Math.log10(2)) + 1;
        return highestBit - Integer.bitCount(i);
    }
}

-2

在Java中,由于求值顺序是定义的,因此我们可以这样做:

public static int countZero(int n) {
    for (int i=1,t=0 ;; i<<=1) {
        if (n==0) return t;
        if (n==(n&=~i)) t++;
    }
}

请注意,这取决于先评估等式的左侧; 在C或C ++中尝试相同的操作,编译器可能会让你看起来很愚蠢,并点燃您的打印机。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接