Quantcast
Channel: How to check if a number is a power of 2 - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Yanara for How to check if a number is a power of 2

$
0
0

There were a number of answers and posted links explaining why the n & (n-1) == 0 works for powers of 2, but I couldn't find any explanation of why it doesn't work for non-powers of 2, so I'm adding this just for completeness.

For n = 1 (2^0 = 1), 1 & 0 = 0, so we are fine.

For odd n > 1, there are at least 2 bits of 1 (left-most and right-most bits). Now n and n-1 will only differ by the right-most bit, so their &-sum will at least have a 1 on the left-most bit, so n & (n-1) != 0:

n:          1xxxx1  for odd n > 1n-1:        1xxxx0            ------n & (n-1):  1xxxx0 != 0

Now for even n that is not a power of 2, we also have at least 2 bits of 1 (left-most and non-right-most). Here, n and n-1 will differ up to the right-most 1 bit, so their &-sum will also have at least a 1 on the left-most bit:

        right-most 1 bit of n                 vn:          1xxxx100..00 for even nn-1:        1xxxx011..11            ------------n & (n-1):  1xxxx000..00 != 0

Viewing all articles
Browse latest Browse all 38

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>