Thursday, August 28, 2008

How to find whether the given number is a power of 2 in single a single step (without using loops) ?

Ok this is another often repeated question. But unlike the others, this has a legitimate solution.

Before I show you the code for this, I would like to explain a few things first. We are required to find if a number is a power of 2 in just one step. A number would be a power of two if there is exactly one bit that is equal to 1 in its bit pattern (even 1 is a power of 2. 2 raised to the power zero is 1). Now we could use the method that we used to count the number of bits that are 1 in a given number and check if it is equal to 1. However that approach needs many steps and hence wont suffice here.

In a number which is an exact power of 2 only 1 bit is set and all others are zero. Let the position of this 1 bit be MSB. Mathematics rules for binary numbers tells us that if we subtract 1 from this number then the number that we would get would have all its bit starting from the bit position MSB+1 set to 1. For example if the given number num is 8(00001000) then num-1 would be 7 (00000111). Now we notice that these two bit patterns dont have a 1 in the same bit position. Further observation suggests that if we bitwise and (&) both these numbers we would get zero.

It can also be proved that num&(num-1) would be zero only if num is a power of 2. I leave that as an exercise. If you are'nt able to figure out why it is so, then just leave a comment here and I will explain that part too.

Now here is the code:

bool isPowerOf2(int num){
return ((num>0) && (num & (num-1))==0);
}

0 comments: