Да приемем, че имаме int x = 371
, което е в двоичен формат 101110011
. Искам да намеря индекса на най-левия ненастроен бит (в този случай 7) и индекса на най-десния ненастроен бит (в този случай 2). Кой е най-ефективният начин да го направите?
Ето какво имам:
public class BitOperatons {
public static int setBit(int x, int i) {
int y = x | (1 << i);
return y;
}
public static boolean isBitSet(int x, int i) {
int y = setBit(0, i);
return y == (x & y);
}
public static int findLeftMostSetBit(int x) {
for (int i = 31; i >= 0; i--) {
if (isBitSet(x, i))
return i;
}
return -1;
}
public static int findRightMostUnsetBit(int x) {
for (int i = 0; i <= 31; i++) {
if (! isBitSet(x, i))
return i;
}
return -1;
}
public static int findLeftMostUnsetBit(int x) {
int k = findLeftMostSetBit(x);
for (int i = k; i >= 0; i--) {
if (! isBitSet(x, i))
return i;
}
return -1;
}
public static1+ void main(String[] args) {
int x =
(1 << 0) |
(1 << 1) |
(1 << 4) |
(1 << 5) |
(1 << 6) |
(1 << 8);
System.out.println(findLeftMostUnsetBit(x));
System.out.println(findRightMostUnsetBit(x));
}
}
Ако не греша, текущата ми реализация отнема линейно време. Можем ли да се справим по-добре?
Integer.numberOfTrailingZeros
и това е двоично търсене.) - person toto2   schedule 27.06.2011