Power Of Two Or Not Algorithm

The Power of Two or Not Algorithm is a mathematical technique used to determine if a given number is a power of two or not. This algorithm is based on the binary representation of numbers and their properties in computer science, as powers of two are widely used in various computer algorithms, data structures, and memory management. By leveraging the unique characteristics of binary numbers, this algorithm helps in quickly and efficiently identifying if a number is a power of two or not, hence optimizing various computational processes. In the Power of Two or Not Algorithm, the primary approach is to use bitwise operations, specifically the bitwise AND operation. For any given number 'n', if it is a power of two, its binary representation will have only one bit set (i.e., the bit at the position corresponding to the power of two). In this case, (n - 1) will have all the bits set to the right of the bit which is set in 'n'. By performing the bitwise AND operation between 'n' and (n - 1), the result will be zero if 'n' is a power of two, and non-zero otherwise. This simple yet powerful approach allows for the fast identification of powers of two, thereby improving the performance of various computer algorithms and systems that rely on this property.
package Others;

import java.util.Scanner;

/**
 * A utility to check if a given number is power of two or not.
 * For example 8,16 etc.
 */

public class PowerOfTwoOrNot {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int num = sc.nextInt();
        boolean isPowerOfTwo = checkIfPowerOfTwoOrNot(num);
        if (isPowerOfTwo) {
            System.out.println("Number is a power of two");
        } else {
            System.out.println("Number is not a power of two");
        }
        sc.close();
    }


    /**
     * Checks whether given number is power of two or not.
     *
     * @param number
     * @return boolean
     */
    public static boolean checkIfPowerOfTwoOrNot(int number) {
        return number != 0 && ((number & (number - 1)) == 0);
    }
}

LANGUAGE:

DARK MODE: