Skip to content
Advertisement

Checking if a double is a power 2

I’m not sure how to check if a double is a power of 2. This is my code so far:

double x = Double.longBitsToDouble(
    Double.doubleToRawLongBits(n) & Double.doubleToRawLongBits(n - 1)
);

I used the following formula to find if the number is a power of 2:

n & (n - 1) == 0

But its not working.

Advertisement

Answer

To deal with big numbers you can use the BigInteger class:

public boolean isPowerOfTwo(BigInteger n) {
    if (n.compareTo(BigInteger.ZERO) <= 0) {
        return false;
    }
    return (n.and(n.subtract(BigInteger.ONE))).equals(BigInteger.ZERO);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement