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?

You May Also Like:

How to swap two numbers with or without temporary variable in java
Java Program to Swap two numbers using Bitwise XOR Operator?
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number
Java Program to Calculate the Power of a Number
Check whether a number is prime or not
Java Program to displaying prime numbers
Fibonacci series using iterative and recursive approach java program
Find largest and second largest number in the given Array
Java program to Remove Duplicate Elements From an Array
Find common elements between two Arrays
Find largest and smallest number in the given Array
Java Program to find duplicate elements in an Array
Count number of words in a string in java
How would you check if a number is even or odd using bit wise operator in Java?
How to check if String is number in java ?

If you have any feedback or suggestion please feel free to drop in blow comment box. 

Leave a Reply

Your email address will not be published. Required fields are marked *