Program to find whether a number is power of 2
This post will teach you how to find whether a number is power of 2. I am using 2 types of methods to solve this problem.
Method 1 - checkPower
Method 1 - checkPower
- If the number mod 2 not equal to 0, return false.
- Till number greater than 2, number = number/2 and check whether number mod 2 equal to 0 or not.
- If not equal to 0, return false.
- Return true at the end of loop.
Time complexity of the program is O(log n). For better results, a new method is used. It is as follows.
Method 2 - checkPower1
- Find log(number)/log(2).
- If (2^ log(number)/log(2)) equals the given number, it is power of 2. Else not.
Time complexity of the program is O(1).
The program is as follows: -
public class powerOf2 {
public static void main(String args[])
{
int num = 3;
if(checkPower(num))
{
System.out.println(" The number is a power of two");
}
else
{
System.out.println(" The number is not a power of two");
}
if(checkPower1(num))
{
System.out.println(" The number is a power of two");
}
else
{
System.out.println(" The number is not a power of two");
}
}
public static boolean checkPower(int num)
{
if(num%2!=0)
{
return false;
}
while(num>2)
{
num=num/2;
if(num%2!=0)
{
return false;
}
}
return true;
}
public static boolean checkPower1(int num)
{
double num1= (double) num;
int log = (int) (Math.log(num1)/Math.log(2));
if(Math.pow(2, log)==num1)
{
return true;
}
else
{
return false;
}
}
}
Thank you for reading the post. If you have any doubts comment below. All queries will be responded within 1 day.
This comment has been removed by the author.
ReplyDeleteOne more easy method - if (num&(num-1)==0), then it is power of 2. Else not.
ReplyDelete