Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a number < 1 is power of 2?

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
    }
}
like image 214
ggrr Avatar asked May 13 '15 06:05

ggrr


1 Answers

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
}
like image 185
Tagir Valeev Avatar answered Sep 20 '22 01:09

Tagir Valeev