Given an integer, write a function to determine if it is a power of two.

A number is a power of two if it contains exactly one set bit (1) in its binary representation. Examples include 1, 2, 4, 8, 16, and 32.

The solution uses a bit manipulation technique. For any positive power of two number, performing the operation n & (n - 1) removes its only set bit and results in zero. If the result is zero, the number is a power of two; otherwise, it is not.

This approach is highly efficient because it avoids loops and repeated division operations.

Java Solution:

public class PowerOfTwo {

    public static boolean isPowerOfTwo(int number) {

        if (number <= 0) {
            return false;
        }

        return (number & (number - 1)) == 0;
    }

    public static void main(String[] args) {

        int number = 16;

        if (isPowerOfTwo(number)) {
            System.out.println(number + " is a Power of Two.");
        } else {
            System.out.println(number + " is not a Power of Two.");
        }
    }
}

Output: 16 is a Power of Two.

Time Complexity: O(1), since the solution performs a constant number of operations regardless of the input value.

Space Complexity: O(1), as no additional memory is required.

Key Interview Points: • A power of two contains exactly one set bit in its binary representation. • The expression n & (n - 1) removes the rightmost set bit from a number. • The check for number <= 0 is important because zero and negative numbers are not powers of two. • An alternative approach is to repeatedly divide the number by 2 until it becomes 1, but that requires O(log n) time.