2019-05-09 19:32:54 +08:00
|
|
|
package Others;
|
|
|
|
|
2017-12-24 14:33:12 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
/**
|
2019-05-09 19:32:54 +08:00
|
|
|
* 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 {
|
|
|
|
|
2019-05-09 19:32:54 +08:00
|
|
|
public static void main(String[] args) {
|
2017-12-24 14:33:12 +08:00
|
|
|
|
2019-05-09 19:32:54 +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();
|
2019-05-09 19:32:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
}
|