Check if an integer is a power of 2

suggest change

The n & (n - 1) trick is also useful to determine if an integer is a power of 2:

bool power_of_2 = n && !(n & (n - 1));

Note that without the first part of the check (n &&), 0 is incorrectly considered a power of 2. Use this for a non-negative n. A negative value is not a power of two, and the test above is about the bit pattern.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents