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 FReeze FRancis for How to check if a number is a power of 2

$
0
0

for any power of 2, the following also holds.

n&(-n)==n

NOTE: fails for n=0 , so need to check for it
Reason why this works is:
-n is the 2s complement of n. -n will have every bit to the left of rightmost set bit of n flipped compared to n. For powers of 2 there is only one set bit.


Viewing all articles
Browse latest Browse all 38

Trending Articles



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