How can you check if the given number is power of 2?

By | August 17, 2019

In this post we will talk and learn How can you check if the given number is power of 2? using an example.

This can be easily checked using bitwise operators in Java. Firstly, let’s see how a number looks in binary when it is power of two.
From the figure, we can see that only 1 bit is set for all numbers which are exponent of 2.
Let’s now write a method to check if only nth bit of a number is set to true.

public static boolean isPowerOfTwo(int number) {
return (number > 0) && ((number & (number – 1)) == 0);
}

The first condition (number > 0) checks if the number is positive, because the second condition works only for positive numbers.
The second condition ((number & (number – 1)) will return zero for a number which is exponent of two (provided the number is positive). For example, in case of number 32  Thus, through the above code, we are checking if the number is positive and is power of two.

Let’s write a complete example

Output of above programs for few inputs::

That’s all about How can you check if the given number is power of 2?
If you have any feedback or suggestion please feel free to drop in blow comment box.