Friday, July 5, 2024

Check if a Number Is Power of 2 in Java

Check if a Number Is Power of 2 in Java

In this article, we will explore different approaches to check if a given number is a power of 2 in Java. We will cover the following methods:

  • Loop Division
  • Using Bitwise & Operations
  • Counting Set Bits
  • Using Integer.highestOneBit()
  • Using Logarithm

1. Loop Division


This approach involves continuously dividing the number by 2 and checking if the remainder is ever not zero.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        while (n % 2 == 0) {
            n /= 2;
        }
        return n == 1;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero. If it is, we return false.
  • We repeatedly divide the number by 2 as long as it is even.
  • Finally, we check if the resulting number is 1.

2. Using Bitwise & Operations


This method utilizes the property that powers of 2 have exactly one bit set in their binary representation.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

◉ We check if the number is greater than zero.
◉ We use the bitwise AND operation to check if the number has only one bit set.

3. Counting Set Bits


This approach counts the number of set bits (1s) in the binary representation of the number.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n > 0) {
            count += (n & 1);
            n >>= 1;
        }
        return count == 1;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero.
  • We count the number of set bits by checking the least significant bit and right-shifting the number.
  • We return true if the count of set bits is 1.

4. Using Integer.highestOneBit()


This method uses the Integer.highestOneBit() function to check if the number is a power of 2.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        return n > 0 && Integer.highestOneBit(n) == n;
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is greater than zero.
  • We use the Integer.highestOneBit() method to get the highest bit of the number.
  • We check if this highest one-bit is equal to the number itself.

5. Using Logarithm


This approach uses the mathematical property that if a number is a power of 2, its logarithm base 2 should be an integer.

public class PowerOf2 {
    public static boolean isPowerOfTwo(int n) {
        if (n <= 0) {
            return false;
        }
        double log2 = Math.log(n) / Math.log(2);
        return log2 == Math.floor(log2);
    }
 
    public static void main(String[] args) {
        System.out.println(isPowerOfTwo(16)); // true
        System.out.println(isPowerOfTwo(18)); // false
    }
}

In the above code:

  • We check if the number is less than or equal to zero.
  • We calculate the logarithm base 2 of the number.
  • We check if the result is an integer.

6. Summary


Method Advantages  Disadvantages 
Loop Division
  • Simple to understand and implement.
  • Directly checks divisibility by 2.
  • Less efficient for large numbers due to multiple divisions.
Using Bitwise & Operations 
  • Very efficient with constant time complexity O(1).
  • Utilizes fast bitwise operations. 
  • Requires understanding of bitwise operations. 
Counting Set Bits 
  • Conceptually simple and easy to understand. 
  • Less efficient due to the need to count all set bits.
  • Time complexity is O(log n). 
Using Integer.highestOneBit() 
  • Efficient and uses a single built-in method.
  • Constant time complexity O(1). 
  • 5Depends on an understanding of the Integer.highestOneBit() method. 
Using Logarithm
  • 3Uses mathematical properties and is easy to understand. 
  • Less efficient due to the use of floating-point operations.
  • Potential issues with floating-point precision. 

Source: javacodegeeks.com

Related Posts

0 comments:

Post a Comment