Monday, April 13, 2009

pow(2) ?

Given a natural number, how do we check if it is power of 2?

So, lets say, we were given 388. How do we write a program to check if the number is a power of 2?

Hint:
given n, n and (n - 1) don't share any bits in common.
Still don't get it?
if ((n & (n - 1)) == 0) {
//pow of 2!
}
Lets see this with a simple example.
let n = 3.
So, n = 011
and n - 1 = 010
So, n & (n - 1) = 010

Consider 4.
n & (n - 1) = 100 & 011 = 000

So, there u go :)

No comments:

Post a Comment