Find if an integer is a power of 2

© Parineeth M R

Question 30. Find if an integer is a power of 2 using bit wise operators


The condition (x & (x-1) == 0) checks if an integer is a power of 2 or not. From the previous question, we know that x & (x-1) will reset the first bit that has a value of 1 from the right to 0. If x is a power of 2, then only one of the bits will be set to 1 and all the remaining bits will be set to 0 (for instance, 8 is a power of 2 and 8 in binary is 1000). So x & (x-1) will reset the only bit that has a value of 1 resulting in 0.

x & (x-1) == 0 however incorrectly indicates that 0 is also a power of 2, since (0 & (0 – 1) ) = (0 & 0xffffffff) = 0. Since 0 is not a power of 2, we modify the condition as shown below

C/C++


(x != 0) && (x & (x-1) == 0)


Java


(x != 0) && ((x & (x-1)) == 0)


Python


(x != 0) and ((x & (x-1)) == 0)