Core 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

MethodAdvantagesDisadvantages
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).
  • Depends on an understanding of the Integer.highestOneBit() method.
Using Logarithm
  • Uses mathematical properties and is easy to understand.
  • Less efficient due to the use of floating-point operations.
  • Potential issues with floating-point precision.

7. Conclusion

By using these different methods, you can efficiently check if a given number is a power of 2 in Java. Each method has its advantages and can be chosen based on the specific requirements and constraints of your problem.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button