<p>I need a function like this:</p>
<pre><code>// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) =&gt; true  
// is_power_of_2(3) =&gt; false
bool is_power_of_2(int n);
</code></pre>
<p>Can anyone suggest how I could write this?</p>

A power of two will have just one bit set (for unsigned numbers). Something like
```
```
bool powerOfTwo = !(x == 0) && !(x & (x - 1));
```
```
Will work fine; one less than a power of two is all 1s in the less significant bits, so must AND to 0 bitwise.
As I was assuming unsigned numbers, the == 0 test (that I originally forgot, sorry) is adequate. You may want a > 0 test if you're using signed integers.