-2

Consider this program to determine if a given number is a power of 2.

class Solution{
    
    // Function to check if given number n is a power of two.
    public static boolean isPowerofTwo(long n){
        
        // Your code here
        float x = (float)Math.log(n)/(float)Math.log(2);
        System.out.println(x);
        if(x%1==0)
           return true;
        return false;
        
        
    }
    
}

Then consider n =1073741824, while the output should be 30,it gives 29.999998.

Ananya
  • 1
  • 1
  • 1
    This is as expected. Possily worse when you use `float` then if you used `double`. – Ole V.V. May 12 '23 at 05:56
  • 2
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ole V.V. May 12 '23 at 05:57
  • 1
    Using floating point math to test if a power of 2 is a bad idea – Maurice Perry May 12 '23 at 05:59
  • 2
    Does this answer your question? [How to check if a number is a power of 2](https://stackoverflow.com/questions/600293/how-to-check-if-a-number-is-a-power-of-2) I know it’s a C# question, but most answers should work in Java too. Or look at [this one](https://stackoverflow.com/questions/22026924/java-finding-if-number-is-power-of-2). – Ole V.V. May 12 '23 at 05:59
  • 3
    or `Long.bitCount(n) == 1` (for strictly positive numbers) || why casting to `float`? – user16320675 May 12 '23 at 06:04
  • 1
    @user16320675 Nice. So `n > 0 && Long.bitCount(n) == 1` will cover all cases. (In fact the only case where your code does not work correctly is the case where the single 1 is the sign bit.) – Ole V.V. May 12 '23 at 06:07
  • 1
    `n > 0` is actually only needed to *avoid* `n == Long.MIN_VALUE` - the only non-positive value with exactly one bit set – user16320675 May 12 '23 at 06:11

1 Answers1

0

Don't use floating point math to determine if a number is a power of 2. Use this instead:

return n > 0 && (n&(n-1)) == 0;
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24