How to Check if a Number is a Power of Two

How to check if a number is a power of two.  Give an integer, write a function to check if it is a power of two.

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.

Power of Two LeetCode

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.

 


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.

Power of 2 | Bit Manipulation – Java Code