Java : Program to check if a given integer number is power of two.

/*
 * @author : P programs
 * Check if a given integer number is power of 2 or not.
 * Exp :8 is a power of 2
 *     :10 is not a power of 2
 *     :32 is a power of 2.
 *
 * To find whether a number is power of 2 or not, we can do a AND operation between number and number-1 ,
 * if AND operation results in 0 then it's a valid power of 2 else its not.
*/

import java.util.*;

public class FindIntegerPowOf2 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.print("Enter valid Integer number : - ");
int validIntNumber = sc.nextInt();
int result = pow2(validIntNumber);

System.out.println(result);

if (result ==0){
System.out.println("Number is a valid power of 2 ");
}else
{
System.out.println("Number is not a valid power of 2 ");
}


}

public static int pow2(int number){

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

}

}

No comments:

Post a Comment

πŸ””Announcement : Visit the new website/blog πŸ””

πŸ””πŸ””πŸ”” Announcement :  Visit the new website/blog πŸ””πŸ””πŸ”” Dear readers, Thank you for reading my blog. If you could have used the little info...