Tuesday 22 December 2015

To check if a number is power of 2 or not

There is a one line solution for this but before that let us see the basic explanation:

1. You can simply take the log of the number on base 2 and if you get an integer then the number is power of 2.

2. All the powers of two have only one bit set. So, if we count the number of set bits for a given number and if it comes out to be 1 then the number is a power of 2.

3. Alternatively, we can keep dividing the number by 2, iteratively. If in any iteration n%2 becomes non-zero then n is not a power of 2. If n becomes 1 then number is a power of 2. Here's the function to do this:


#include<stdio.h>
 
int isPowerOf2(int n)
{
  if (n == 0)
    return 0;
  while (n != 1)
  {
    if (n%2 != 0)
      return 0;
    n = n/2;
  }
  return 1;
}

4. Here is a One Liner, it works on the following concept:
If we subtract a power of 2 by 1 then set becomes unset and all the unset bits after it becomes set.
For eg: 16 (10000) , 32 (100000)
15 -> 01111
31 -> 011111
So, if a number is a power of 2 then 'bitwise &' of n and n-1 will be 0. Hence the expression n&(n-1) can decide whether a number is power of 2 or not. Please note that it does not give correct answer for n=0.
Here is the implementation :

#include<stdio.h>
 
int isPowerOf2 (int n)
{
  if(n==0) 
     return 0;
  else   
     return  (!(n&(n-1)));
}

No comments:

Post a Comment