Program to find whether a given number is power of 2 in java

0



 This is one of the most asked question in interviews. Where the interviewer provide you the number and you have to find where the number is power of two of not .


Example :

Input : 128

Output : Yes

Explanation : 2^7 =128, Hence it is power of two.




public class PowerOfTwo {
public static int countbit(int n)
{
int count=0;
while(n>0)
{
n=n&(n-1);
count++;
}
return count;
}
public static void main(String args[])
{
int n=128;
int count=countbit(n);
if(count==1)
{
System.out.println("Power of two");
}
else{
System.out.println("Not power of two");
}
}
}




Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !