JavaAlgorithms/Others/PowerOfTwoOrNot.java

37 lines
871 B
Java
Raw Normal View History

package Others;
2017-12-24 14:33:12 +08:00
import java.util.Scanner;
/**
* A utility to check if a given number is power of two or not.
* For example 8,16 etc.
*/
2017-12-24 14:33:12 +08:00
public class PowerOfTwoOrNot {
public static void main(String[] args) {
2017-12-24 14:33:12 +08:00
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");
}
2020-01-29 00:34:52 +08:00
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);
}
2017-12-24 14:33:12 +08:00
}