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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public boolean isPowerOfTwo(int n) { /* * If number is less than or equal to * zero then return false. */ if (n <= 0) return false; while (n % 2 == 0) n = n/2; return n == 1; } |