How to determine if an integer is a power of 2

This particular example is in C, but it can easily be adapted to any other programming language. Can you figure out how it works? 🙂

int isPowerOfTwo(int n)
  return n && !(n & n - 1);

Leave a Reply

Your email address will not be published. Required fields are marked *