public final class Pow2 {
public static final int MAX_POW2 = 1 << 30;
public Pow2() {
}
public static int roundToPowerOfTwo(int value) {
if (value > MAX_POW2 ) {
throw new IllegalArgumentException("There is no larger power of 2 int for value:" + value + " since it exceeds 2^31.");
} else if (value < 0) {
throw new IllegalArgumentException("Given value:" + value + ". Expecting value >= 0.");
} else {
int nextPow2 = 1 << 32 - Integer.numberOfLeadingZeros(value - 1);
return nextPow2;
}
}
public static boolean isPowerOfTwo(int value) {
return (value & value - 1) == 0;
}
}
这里的roundToPowerOfTwo方法很棒啊,不需要使用循环了,使用循环的可以如下:
public static int roundToPowerOfTwo(int value) {
if (value > MAX_POW2 ) {
throw new IllegalArgumentException("There is no larger power of 2 int for value:" + value + " since it exceeds 2^31.");
} else if (value < 0) {
throw new IllegalArgumentException("Given value:" + value + ". Expecting value >= 0.");
} else {
int nextPow2 = 1;
while (nextPow2 < value) {
nextPow2 <<= 1;
}
return nextPow2;
}
}