Make delicious recipes!

Check if a number is power of 2

This can be checked in just one line of code as follows:

if (n & (n-1) == 0) return true;


n-1 = 3
n & n-1 = 0 (AND of 100 with 011)

n-1 = 8
n & n-1 = 9 (AND of 1001 with 1000)

n-1 = 15
n & n-1 = 0 (AND of 10000 with 01111)

This works because if a number is power of 2, then it has only one 1 in it's binary representation.
Due to this, n-1 gives 1s at all places right of original 1s place.
Since, original number had only one 1 and that is absent in n-1, the ANDing of the two always gives 0

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal