patternjavaModerate
Calculating int next power of two
Viewed 0 times
nextpowercalculatingtwoint
Problem
Here is one of the possible solutions:
As in your opinion is it good enough or may you suggest better one?
public static int getNextPowerOfTwo(int value) {
int result = value;
result -= 1;
result |= result >> 16;
result |= result >> 8;
result |= result >> 4;
result |= result >> 2;
result |= result >> 1;
return result + 1;
}As in your opinion is it good enough or may you suggest better one?
Solution
Java has
Integer.highestOneBit that can make this a bit simpler:int highestOneBit = Integer.highestOneBit(value);
if (value == highestOneBit) {
return value;
}
return highestOneBit << 1;Code Snippets
int highestOneBit = Integer.highestOneBit(value);
if (value == highestOneBit) {
return value;
}
return highestOneBit << 1;Context
StackExchange Code Review Q#157503, answer score: 16
Revisions (0)
No revisions yet.