How to Check if a Number is a Power of 2

How to check if a number is a power of 2.  To understand this question, let’s take some example.

Example –

Input – 16   – 16 is a power of 2 (2^4).

Input – 15 – 15 is not a power of 2.

Input – 32- 32 is a power of 2 (2^5).

We can use multiple approaches to check whether a number is a power of 2 or not.

How to Check if a Number is a Power of 2

 

Method 1 : Check whether a number is perfectly divisible by 2.

In this approach, We’ll check whether a number is perfectly divisible by 2. If a number is perfectly divisible by 2 then it’s remainder is 0.

We’ll repeat this step until n becomes 1. In each step, we check if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

Method 2 : Bit Manipulation

Subscribe Our Tutorials

Get Latest Updates on Facebook

How to Check if a Number is a Power of 2

How to Check if a Number is a Power of 2

Let’s consider the binary representation of any number that is a power of 2. We’ll find only one bit is set in their binary representation.

And number which is one less has following binary representation

If we do the bitwise AND of a number which is a power of 2 and a number which is one less than the number (one less than the number which is a power of 2) the result will be 0.

We have discussed two approaches to check whether a number is a power of 2 or not. Let’s implement both the approaches in multiple programming languages.

C Code to Check whether a Number is a Power of 2

METHOD 1: Check if a number is perfectly divisible by 2

METHOD 2 – Bit Manipulation

Java Code to Check if a Number is a Power of 2

METHOD 1: Check if a number is perfectly divisible by 2

METHOD 2 – Bit Manipulation

WebRewrite

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , . Bookmark the permalink.