Find if a number is a power of two in java

Find if a number is a power of two in java

You can determine whether a number is a power of two in Java by using bitwise operations. Here's a method to check if a given number is a power of two:

public class PowerOfTwoChecker {
    public static void main(String[] args) {
        int numberToCheck = 16; // Replace with the number you want to check
        boolean isPowerOfTwo = isPowerOfTwo(numberToCheck);

        if (isPowerOfTwo) {
            System.out.println(numberToCheck + " is a power of two.");
        } else {
            System.out.println(numberToCheck + " is not a power of two.");
        }
    }

    public static boolean isPowerOfTwo(int number) {
        // A power of two in binary has only one '1' bit set. For example: 2^3 = 8 (binary: 1000)
        // If we subtract 1 from a power of two, all bits to the right of the '1' bit become '1'.
        // For example: 8 - 1 = 7 (binary: 0111)
        // So, if we perform a bitwise AND operation between a power of two and one less,
        // the result should be 0.
        // For example: 8 & 7 = 0
        return (number > 0) && ((number & (number - 1)) == 0);
    }
}

In this code:

  • The isPowerOfTwo method takes an integer number as input.
  • It checks if the number is greater than zero (to handle the case where the number is not a positive integer).
  • It performs a bitwise AND operation between the number and (number - 1).
  • If the result of the bitwise AND operation is zero, the number is a power of two because there is only one '1' bit set in its binary representation.

This method efficiently determines if a number is a power of two without requiring exponentiation or iteration. It works for both positive and negative integers and zero.


More Tags

retain-cycle yarnpkg md5sum angular-aot splash-screen android-studio-import range countvectorizer java-time ef-core-2.0

More Java Questions

More Physical chemistry Calculators

More Retirement Calculators

More Stoichiometry Calculators

More Financial Calculators