for example: 0.5 and 0.25 is power of 2 but 0.3 is not, also I know checking if integer is power of 2 is easy, but how to find if number is power of 2 if the number < 1?
public bool isPowerOf2(float number){
if(number>1){
//easy to write
}else if(number==1){
return true;
}else{
//hard to write
}
}
Try this solution:
public boolean isPowerOf2(float number){
if(number>1){
//easy to write
}else if(number==1){
return true;
}else if(number>0){
return isPowerOf2(1.0f/number);
}else
return false;
}
By the way you can solve this simply by checking the bits of float binary representation:
public static boolean isPowerOfTwo(float i) {
int bits = Float.floatToIntBits(i);
if((bits & ((1 << 23)-1)) != 0)
return ((bits & (bits-1)) == 0); // denormalized number
int power = bits >>> 23;
return power > 0 && power < 255; // 255 = Infinity; higher values = negative numbers
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With