Tuesday, 30 April 2013

tit bits - power of 2


To check whether a number is a power of 2

int isPowerOfTwo(unsigned n)
{  
return n && (! (n & (n-1)) ); 
}

How it works:

If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111

n & (n-1) will be 0 
!(n & (n-1)) will be 1 in power of 2 case else 0

logical and with the number will give the result.

Why we need to do logical and with the number ???

n && (! (n & (n-1)) )

Ans: To handle the case n=0

Guys are u OK with this method

There are some other methods which will be interesting

Example: power of 2 numbers will be having only one bit set.

Just we need to count the number of 1s.

In interview if u were asked to check whether "00100000" is a power of 2 then you can straight away tell the answer yes.

No comments:

Post a Comment