Java 获取数字最左边0位的位置

Java 获取数字最左边0位的位置,java,bitwise-operators,Java,Bitwise Operators,我试图得到整数0的最左边的位置 int a = 83 例如,83的二进制是1010011,所以我们有最左边的位0的位置是第6位。我想知道是否只有使用位运算符才能找到答案?据我所知,您可以使用位运算符,但单独使用是不行的。您必须使用条件运算符来获取输出,因为程序必须从右向左检查最后一次出现的0或从左向右检查第一次出现的0。您可以执行以下操作: int a = 83 int mask = 1; // This loop finds the leftmost 1 bi

我试图得到整数0的最左边的位置

    int a = 83

例如,83的二进制是1010011,所以我们有最左边的位0的位置是第6位。我想知道是否只有使用位运算符才能找到答案?

据我所知,您可以使用位运算符,但单独使用是不行的。您必须使用条件运算符来获取输出,因为程序必须从右向左检查最后一次出现的0或从左向右检查第一次出现的0。

您可以执行以下操作:

    int a = 83
    int mask = 1;
    // This loop finds the leftmost 1 bit
    while(a > mask) 
        mask <<= 1;
    mask >>= 1;
    // This loop starts from the leftmost 1 bit and searches for the first 0 going right
    while((a & mask) != 0) 
        mask >>= 1;

    System.out.println(Math.log(mask) / Math.log(2) + 1); // 6
inta=83
int-mask=1;
//此循环查找最左边的1位
while(a>掩码)
掩码=1;
//此循环从最左边的1位开始,搜索向右移动的第一个0
而((a和掩码)!=0)
掩码>>=1;
System.out.println(Math.log(mask)/Math.log(2)+1);//6.
最后一个“log”部分是给出最左边0位TL的位置索引所必需的;DR

private static int leftmostZeroBit(int a) {
    int b = Integer.highestOneBit(a);
    return (b == 0 ? -1 : 31 - Integer.numberOfLeadingZeros(a ^ b ^ (b - 1)));
}

private static int leftmostZeroBit(long a) {
    long b = Long.highestOneBit(a);
    return (b == 0 ? -1 : 63 - Long.numberOfLeadingZeros(a ^ b ^ (b - 1)));
}
解释

不知道这与简单的位搜索循环相比是否有效,但您可以使用以下方法来帮助:

它们都使用位操作,因此所需的迭代次数少于32次(如果使用
Long
版本,则为64次)

给定一个示例输入值
1101011
,我们希望将其转换为
0010100

请记住,
int
有32位,因此它们的左边有25个0位,因此要反转它,我们需要使用掩码
1111111
进行异或

该掩码可以通过调用
highestOneBit()
来计算,这给了我们
1000000
,减去1得到
0111111
,然后将它们组合起来得到掩码

完成异或运算并获得
0010100
后,我们计算
31-numberOfLeadingZeros()
以找到前导1位的位置,在本例中为4

然后,我们可以定义,对于无效输入,我们希望结果为
-1

  • 000
    无效,因为没有不带1位的最左边的0位
  • 111
    无效,因为1位之后没有0位
这给了我们答案顶部的代码

测试

public static void main(String[] args) {
    test(0x6B); // example in answer
    test(0x53); // example in question (83)
    test(0x29);
    test(0x14);
    test(0x0A);
    test(0x05);
    test(0x02);
    test(0x01);
    test(0x00);
    test(0x80000000);
    test(0xFFFFFFFE);
}
private static void test(int a) {
    System.out.printf("%32s: %d%n", Integer.toBinaryString(a), leftmostZeroBit(a));
}
输出

public static void main(String[] args) {
    test(0x6B); // example in answer
    test(0x53); // example in question (83)
    test(0x29);
    test(0x14);
    test(0x0A);
    test(0x05);
    test(0x02);
    test(0x01);
    test(0x00);
    test(0x80000000);
    test(0xFFFFFFFE);
}
private static void test(int a) {
    System.out.printf("%32s: %d%n", Integer.toBinaryString(a), leftmostZeroBit(a));
}
1101011:4
1010011: 5
101001: 4
10100: 3
1010: 2
101: 1
10: 0
1: -1
0: -1
10000000000000000000000000000000: 30
11111111111111111111111111111110: 0

Here:()您可以尝试利用此方法。但是,仅通过位运算符是不可能的。用于什么目的?注意:你的描述不准确。您似乎正在查找最左侧1位右侧的最左侧0位。