November 18, 2013

Interview Question - Write an algorithm to determine if n is a power of 2

If I have the idea correctly, you can actually do this in constant time.

First piece of useful information: Any power of 2 is represented in memory as 0...010...0

Examples:
2 is 00000010
4 is 00000100
8 is 00001000
16 is 00010000

Second piece of useful information: x & (x - 1) is a neat little hack that will return x with its least significant bit cleared out.
What does that do for the examples above?  Just makes them all 0!

So here's the code I wrote:

bool IsPowerOf2(int x) {
   return x > 0 && (x & (x - 1)) == 0;
}

///Update: Crap. This was on stackoverflow already.  Oh well