DEV Community

Discussion on: Power of Two - LeetCode

Collapse
 
ravi1512 profile image
Ravi Mishra

There's an interesting bit property that we can use to solve this. If you AND a number with number - 1, and it's 0 then it is a power of 2. Binary representation of any number which is a power of 2 will have only one set bit and the number less than that will have all bits set except the left most bit. Take 32 for example
32 - 100000
31 - 011111
32 & 31 - 000000

This property won't hold true for numbers which aren't power of 2.