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)));
}
说明
不知道这与简单的位搜索循环相比是否有效,但您可以使用以下方法来提供帮助:
Integer.highestOneBit(int i)
Integer.numberOfLeadingZeros(int i)
它们每个都使用位操作,因此它们需要少于 32 次迭代(如果使用 Long 版本,则需要 64 次迭代)。
给定一个示例输入值1101011,我们希望将其反转为0010100。
请记住,int 有 32 位,因此它们的左侧有 25 个 0 位,因此要反转它,我们需要与掩码 1111111 进行 XOR。
这个掩码可以通过调用highestOneBit()来计算,得到1000000,减去1得到0111111,然后将它们组合得到掩码。
一旦我们完成了 XOR 并得到 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));
}
输出
1101011: 4
1010011: 5
101001: 4
10100: 3
1010: 2
101: 1
10: 0
1: -1
0: -1
10000000000000000000000000000000: 30
11111111111111111111111111111110: 0