Calculating log to the base 2 in java gives inaccurate results

112 Views Asked by At

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.

1

There are 1 best solutions below

0
Maurice Perry On

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;