如果我在Java中有一个整数,如何计算除前导零外有多少个零位?
我们知道Java中的整数有32位,但是仅仅计算数字中设置的位数然后从32中减去并不能给我想要的结果,因为这也会包括前导零。
例如,数字5有一个零位,因为它在二进制中是101
。
如果我在Java中有一个整数,如何计算除前导零外有多少个零位?
我们知道Java中的整数有32位,但是仅仅计算数字中设置的位数然后从32中减去并不能给我想要的结果,因为这也会包括前导零。
例如,数字5有一个零位,因为它在二进制中是101
。
public static int countNonleadingZeroBits(int i)
{
int result = 0;
while (i != 0)
{
if (i & 1 == 0)
{
result += 1;
}
i >>>= 1;
}
return result;
}
这就是我会做的。
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);
}
计算您的数字中“位”(bits)的总数,然后从位数总数中减去1的数量。
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);
}
}
在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++;
}
}